SpringSecurity安全框架学习笔记 -基本认识以及使用方法

前言

这个学习笔记系列还在继续,Spring Security是我在写项目途中需要一个安全框架,并顺手学习下来,我由于看过这类教程看的有些迷糊,特此分享给大家,并做一个系统的梳理。

Spring Security 相对 shiro来说会有点太重了,不过技多不压身,废话不多说我们直接开始。

简介

Spring Security安全框架是Spring全家桶中一个比较重要且功能实用的框架,能使我们快速完成权限验证以及权限认证,有兴趣了解官方教程的可以点这:Spring Security官方文档

笔记环境

运行环境:JDK8
开发工具(IDE):IDEA(2020.2.3)
项目构建:Maven
相关依赖:MyBatis-Plus、SpringBoot
数据库:MySQL
前端框架:Vue2.0
项目类型:前后端分离项目

安装

我们项目使用Maven来部署,并添加以下依赖。


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--spring security依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
    </dependencies>

里面有Spring Security依赖,可以自行复制。

控制器

为了笔记需要,我们在controller包下创建一个IndexController类并写好一个接口

/** 这是一个初始化控制器
 *
 */
@Controller
public class IndexController {

    @RequestMapping("/")
    public String index(){
        return "index";
    }
    @RequestMapping("/main")
    @ResponseBody
    public String msg(){
        return "这是Marinda_Speed的文章";
    }


}

初始化效果

当Spring Security成功依赖后,启动项目输入默认地址都会被拦截并重定向为:http://127.0.0.1/login,并且控制台还会输出那么一段话。

控制台如下:

Using generated security password: UUID字符串

页面效果
页面

不要紧张,因为Spring Security本身拥有很多 拦截器 相信小伙伴们对于拦截器也不陌生,这里简单讲一下就是把坊问路径以及坊问资源全部进行拦截处理
登陆后则立刻 放行

基础登录

Spring Security 默认登录账户和密码
用户名: user
密码:控制台得到的那个UUID

登录完成之后我们就可以正常访问拉!

这时候就会有小伙伴问了:我可不可以自定义我的登录页面呢?自定义账号密码登录呢?,答案是可以的,官方很贴心的封装了很多配置。

我们这里使用的是SpringBoot,那我们通过注解来进行配置

自定义配置

在config包下创建一个名为SecurityConfig的配置类继承WebSecurityConfigurerAdapter并实现

  • configure(AuthenticationManagerBuilder auth) 身份验证
  • configure(WebSecurity web) 拦截器一般处理放行或者限制指定路径进行验证
  • configure(HttpSecurity http) 身份授权
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    
    /**
     * 配置验证登录-> 账户以及权限设置
     *
     * @param auth 身份验证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    }

    /**
     * 拦截器 -> 路径拦截放行或者验证
     *
     * @param web 网络
     * @throws Exception 异常
     */
    @Override
    public void configure(WebSecurity web) throws Exception {

    }

    /**
     * 拦截器 -> 授权管理
     *
     * @param http http
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

    }
}

此时我们已经有了一个Spring Security配置类了,那我们就开始自定义配置。

自定义用户名密码

一般数据是从数据库里面调出来的,我们先做一个基础的Demo

package cn.marinda.resturants.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    /**
     * 配置验证登录-> 账户以及权限设置
     *
     * @param auth 身份验证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        配置用户
        auth.inMemoryAuthentication().withUser("admin").password("123123").roles("main");
        auth.inMemoryAuthentication().withUser("user").password("123").roles("staff");

    }

    /**
     * 拦截器 -> 路径拦截放行或者验证
     *
     * @param web 网络
     * @throws Exception 异常
     */
    @Override
    public void configure(WebSecurity web) throws Exception {

    }

    /**
     * 拦截器 -> 授权管理
     *
     * @param http http
     * @throws Exception 异常
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        放行/路径不需要授权
        http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/main").hasRole("main");

//        开启表单验证
        http.formLogin();
    }
}

我们访问:http://127.0.0.1/main重定向到login页。
输入信息:
用户名:admin
密码:123123

异常解析

请求访问结果:
结果
后台报错

There is no PasswordEncoder mapped for the id "null"

这段话什么意思呢?,我们翻译一下:没有为id“null”映射的PasswordEncoder
那我们明白了,需要配置一下PasswordEncoder,那我们在配置文件中新增

    /**
     * 密码编码器
     *
     * @return {@link PasswordEncoder}
     */
    @Bean
    BCryptPasswordEncoder getPwordEncoder(){
//        我们使用的是BCryptPasswordEncoder方式
        return new BCryptPasswordEncoder();
    }

并在Auth身份验证处修改一下密码处理

    /**
     * 配置验证登录-> 账户以及权限设置
     *
     * @param auth 身份验证
     * @throws Exception 异常
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        配置用户
        auth.inMemoryAuthentication().withUser("admin").password(getPwordEncoder().encode("123123")).roles("main");
        auth.inMemoryAuthentication().withUser("user").password(getPwordEncoder().encode("123")).roles("staff");

    }

然后我们再来看看效果。

再次登录

打开http://127.0.0.1/main 重定向到http://127.0.0.1/login
在表单中输入以下信息:
用户名:admin
密码:123123 (此时这里已经做了一个密码加密,我们明文密码登录就行)

效果如下
在这里插入图片描述
成功访问!

细心的小伙伴们会发现我们在账户授权里面还定义了一个user我们来试试用这个登录

效果如下:
403
登陆后发生了一个403权限异常,那我们再来解析一下为什么?

细心的小伙伴们发现了,admin用户有main的权限,而user只有staff权限,并没有main权限,所以被限制访问了。

结束语

今天我们讲解了一下Spring Security的基本使用方法和认识了Spring Security框架。

  • 如果对你有帮助的话可以给我点赞收藏,十分感谢
  • 致力做学习笔记分享给大家
  • 可以转载 需标明 出处 本文链接。
  • 笔者一个开源项目:餐饮管理系统 希望大家可以点一下star

感谢你的观看。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security是一个强大的安全框架,它提供了很多功能来保护应用程序免受各种攻击。下面是使用Spring Security基本步骤: 1. 添加Spring Security依赖 在Maven项目中,在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-web</artifactId> <version>5.3.3.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-config</artifactId> <version>5.3.3.RELEASE</version> </dependency> ``` 2. 配置Spring Security 创建一个Spring Security配置类,以配置身份验证和授权规则。可以使用以下注释来启用Spring Security: ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 配置 } ``` 然后,可以覆盖configure()方法来定义身份验证和授权规则: ```java @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/user/**").hasAnyRole("USER", "ADMIN") .antMatchers("/**").permitAll() .and().formLogin(); } ``` 上面的代码定义了如下规则: - /admin/**路径需要ADMIN角色才能访问 - /user/**路径需要USER或ADMIN角色才能访问 - 其他路径允许所有人访问 - 通过表单登录进行身份验证 3. 配置用户信息 可以使用内存、数据库或LDAP等不同的方法来存储和管理用户信息。在内存中存储用户信息的示例代码如下: ```java @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER") .and() .withUser("admin").password("{noop}password").roles("ADMIN"); } ``` 上面的代码定义了两个用户: - 用户名为user,密码为password,角色为USER - 用户名为admin,密码为password,角色为ADMIN 4. 配置日志 可以使用日志记录Spring Security的操作和错误。例如,可以使用以下配置来记录Spring Security的操作: ```xml <configuration> <appender name="security" class="org.apache.log4j.RollingFileAppender"> <param name="File" value="/var/log/security.log"/> <param name="MaxFileSize" value="10MB"/> <param name="MaxBackupIndex" value="10"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{ISO8601} %-5p [%t] %c{1} - %m%n"/> </layout> </appender> <logger name="org.springframework.security" additivity="false"> <level value="DEBUG"/> <appender-ref ref="security"/> </logger> </configuration> ``` 上面的配置将Spring Security的日志记录到/var/log/security.log文件中。 以上是使用Spring Security基本步骤,可以根据需要进行更多的配置和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值