Spring Security 快速上手

x33g5p2x  于2022-02-12 转载在 Spring  
字(23.5k)|赞(0)|评价(0)|浏览(277)

Spring Security 框架简介

Spring Security 说明

  1. Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案

  2. 关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证**(Authentication)和用户授权(Authorization)两个部分**,这两点也是 Spring Security 重要核心功能。

  3. **用户认证:**验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。通俗点说就是系统认为用户是否能登录。

  4. **用户授权:**验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。通俗点讲就是系统判断用户是否有权限去做某些事情。

Spring Security 官网

Spring Security 特点

  1. 和 Spring 无缝整合

  2. 重量级、全面的权限控制

  3. 专门为 Web 开发而设计

  4. 旧版本不能脱离 Web 环境使用。

  5. 新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。

Spring Security 对比 Shiro

Shiro 简介
  1. Shrio 是Apache 旗下的轻量级权限控制框架

特点:

  1. 轻量级。Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。

  2. 通用性:

  3. 好处:不局限于 Web 环境,可以脱离 Web 环境使用。

  4. 缺陷:在 Web 环境下一些特定的需求需要手动编写代码定制。

总结

Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理这个领域,一直是 Shiro 的天下。

相对于 Shiro,在 SSM 中整合 Spring Security 都是比较麻烦的操作,所以,SpringSecurity 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有Spring Security 多,但是对于大部分项目而言,Shiro 也够用了)。

自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了自动化配置方案,可以使用更少的配置来使用 Spring Security。

因此,一般来说,常见的安全管理技术栈的组合是这样的:

• SSM + Shiro
• Spring Boot/Spring Cloud + Spring Security

以上只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。

Spring Security 框架快速入门

  1. 搭建spring boot 项目,并引入项目依赖
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
  1. 新建Controller,并配置访问方法
package org.taoguoguo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author taoGuoGuo
 * @description HelloController
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 14:16
 */
@RestController
@RequestMapping("/test")
public class HelloController {

    @GetMapping("hello")
    public String hello(){
        return "hello security";
    }
}
  1. 访问对应的方法,我们发现跳转至了默认的Spring Security 登录页面,用户名默认为 user , 密码为 控制台打印 password

Using generated security password: 22f1f943-b70b-43e9-bf56-adf37851a9e7

Spring Security 用户名密码配置

刚刚我们的密码是在控制台,Spring Security 内置实现的密码登录,那实际工作中我们怎么自己指定用户名密码呢?

常见的方式有三种:

  1. 通过配置文件指定
  2. 通过配置类指定
  3. 通过实现 UserDetailService 接口实现 数据库查询

通过配置文件指定

在 application.properties 中 进行配置

#第一种方式:通过配置文件配置Spring Security用户名密码
spring.security.user.name=taoguoguo
spring.security.user.password=taoguoguo

通过配置类实现 配置用户名密码

新建 SecurityConfig 并 实现 WebSecurityConfigurerAdapter 适配器实现配置重写

package org.taoguoguo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author taoGuoGuo
 * @description SecurityConfig
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 14:55
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //如果缺少密码解析 登陆后会返回当前登陆页面 并报 id 为 null 的错误
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //方式二:通过配置类设置登录用户名和密码,通过auth设置用户名密码
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("taoguoguo");
        auth.inMemoryAuthentication().withUser("taoguoguo").password(password).roles("admin");
    }
}

通过实现 UserDetailService 自定义实现

自定义实现类配置:

  1. 创建配置类,设置使用哪个userDetailService 实现类
package org.taoguoguo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author taoGuoGuo
 * @description SecurityConfig
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:14
 * SpringSecurity 自定义配置
 */
@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置自定义的数据库实现及密码解析器
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
  1. 编写实现类,返回User对象,User对象有用户名密码和操作权限
package org.taoguoguo.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author taoGuoGuo
 * @description MyUserDetailService
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:18
 */
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

    /**
     * 自定义实现类方式查询用户名密码
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        //密码
        String password = passwordEncoder.encode("taoguoguo");
        //权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User("taoguoguo", password, auths);
    }
}

数据库查询认证

  1. 数据库建立 users表
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) COLLATE utf8mb4_general_ci NOT NULL,
  `password` varchar(100) COLLATE utf8mb4_general_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
  1. 项目添加依赖 采用 mybatis-plus
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.taoguoguo</groupId>
    <artifactId>spring-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-security</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <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.4.3</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-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
  1. 增加数据库参数配置
server.port=8111

#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security_db?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
  1. 创建Users实体
package org.taoguoguo.entity;

import lombok.Data;

/**
 * @author taoGuoGuo
 * @description Users
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:51
 */
@Data
public class Users {
    private Integer id;
    private String username;
    private String password;
}
  1. 创建UsersMapper
package org.taoguoguo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Repository;
import org.taoguoguo.entity.Users;

/**
 * @author taoGuoGuo
 * @description UsersMapper
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:53
 */
@Repository
public interface UsersMapper extends BaseMapper<Users> {
}
  1. 修改自定义配置实现类 MyUserDetailService 进行数据库查询
package org.taoguoguo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.taoguoguo.entity.Users;
import org.taoguoguo.mapper.UsersMapper;
import java.util.List;

/**
 * @author taoGuoGuo
 * @description MyUserDetailService
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:18
 */
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;
    /**
     * 自定义实现类方式查询用户名密码
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用usersMapper方法,根据用户名查询数据库
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users users = usersMapper.selectOne(wrapper);
        if(users == null){  //数据库没有该用户名 认证失败
            throw new UsernameNotFoundException("用户名或密码不存在!");
        }
        //权限
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");
        return new User(users.getUsername(), users.getPassword(), auths);
    }
}
  1. 在Spring Boot 配置启动类中进行Mapper注解扫描配置 注入Mapper Bean
package org.taoguoguo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }

}

Spring Security自定义登录页面 及 认证放行

通过重写 webSecurityConfigureAdapter 的 configure(HttpSecurity http) 方法进行配置

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //自定义自己编写登录页面
                .loginPage("/login.html")           //登录页面设置
                .loginProcessingUrl("/user/login")  //登录访问路径
                .defaultSuccessUrl("/test/index")   //登录成功后,跳转路径
                .permitAll()
                .and().authorizeRequests()  //定义请求路径访问规则
                .antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
                .anyRequest().authenticated()   //除此之外任何请求都需要认证
                .and().csrf().disable();    //关闭csrf防护
    }

基于角色或权限的进行访问控制

  • hasAuthority 方法,主要针对某一个权限进行控制访问

如果当前的主体具有指定的权限,则返回 true,否则返回 false

修改配置类,增加.antMatchers("/test/index").hasAuthority("admin") 具备admin权限 才能访问 /test/index路径

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()    //自定义自己编写登录页面
                .loginPage("/login.html")           //登录页面设置
                .loginProcessingUrl("/user/login")  //登录访问路径
                .defaultSuccessUrl("/test/index")   //登录成功后,跳转路径
                .permitAll()
                .and().authorizeRequests()  //定义请求路径访问规则
                .antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
                .antMatchers("/test/index").hasAuthority("admin")   //具备admin权限才能访问 /test/index资源
                .anyRequest().authenticated()   //除此之外任何请求都需要认证
                .and().csrf().disable();    //关闭csrf防护
    }

那这个admin的权限是在哪里指定的呢?其实在之前我们已经提到过,在自定义的登录逻辑中,我们会放置用户所具备的权限信息

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //调用usersMapper方法,根据用户名查询数据库
    QueryWrapper<Users> wrapper = new QueryWrapper<>();
    wrapper.eq("username", username);
    Users users = usersMapper.selectOne(wrapper);
    if(users == null){  //数据库没有该用户名 认证失败
        throw new UsernameNotFoundException("用户名或密码不存在!");
    }
    //权限
    List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin");
    return new User(users.getUsername(), users.getPassword(), auths);
}
  • hasAnyAuthority 方法

如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回true

修改配置类,增加.antMatchers("/test/index").hasAnyAuthority("admin,manager") 具备admin 或 manager其中任一权限 就能访问 /test/index路径

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()    //自定义自己编写登录页面
        .loginPage("/login.html")           //登录页面设置
        .loginProcessingUrl("/user/login")  //登录访问路径
        .defaultSuccessUrl("/test/index")   //登录成功后,跳转路径
        .permitAll()
        .and().authorizeRequests()  //定义请求路径访问规则
        .antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
        .antMatchers("/test/index").hasAnyAuthority("admin,manager")
        .anyRequest().authenticated()   //除此之外任何请求都需要认证
        .and().csrf().disable();    //关闭csrf防护
}
  • hasRole 如果用户具备给定角色就允许访问,否则出现 403 如果当前主体具有指定的角色,则返回 true。

查看源码用法

// hasRole 取出角色相关信息 access 判断是否能够访问
public ExpressionInterceptUrlRegistry hasRole(String role) {
    return access(ExpressionUrlAuthorizationConfigurer.hasRole(role));
}

// 为role 底层拼接 ROLE_ 所以 我们在自定义登录逻辑 赋予权限时 要拼接 ROLE_
private static String hasRole(String role) {
    Assert.notNull(role, "role cannot be null");
    Assert.isTrue(!role.startsWith("ROLE_"),
                  () -> "role should not start with 'ROLE_' since it is automatically inserted. Got '" + role + "'");
    return "hasRole('ROLE_" + role + "')";
}

修改配置类,配置用户具备 deptManager才能访问 /test/index资源

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.formLogin()    //自定义自己编写登录页面
        .loginPage("/login.html")           //登录页面设置
        .loginProcessingUrl("/user/login")  //登录访问路径
        .defaultSuccessUrl("/test/index")   //登录成功后,跳转路径
        .permitAll()
        .and().authorizeRequests()  //定义请求路径访问规则
        .antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
        .antMatchers("/test/index").hasRole("deptManager")
        .anyRequest().authenticated()   //除此之外任何请求都需要认证
        .and().csrf().disable();    //关闭csrf防护
}

给用户配置deptManager角色权限

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    //调用usersMapper方法,根据用户名查询数据库
    QueryWrapper<Users> wrapper = new QueryWrapper<>();
    wrapper.eq("username", username);
    Users users = usersMapper.selectOne(wrapper);
    if(users == null){  //数据库没有该用户名 认证失败
        throw new UsernameNotFoundException("用户名或密码不存在!");
    }
    //权限
    List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_deptManager");
    return new User(users.getUsername(), users.getPassword(), auths);
}
  • hasAnyRole 表示用户具备任何一个条件都可以访问

用法和配置和 hasRole 一致,只不过在配置类中配置多个角色方可访问资源路径,同时给用户角色信息时,给一个或多个即可

Spring Security 自定义403 无权限访问页面

  1. 我们在项目的静态资源文件夹 static 下 新建 unauth.html 自定义的403页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>自定义403页面</title>
</head>
<body>
自定义403页面!
</body>
</html>
  1. 修改访问配置类
http.exceptionHandling().accessDeniedPage("/unauth");

Spring Security 注解使用

@Secured 判断是否具有角色

  1. 开启Spring Security注解功能 @EnableGlobalMethodSecurity(securedEnabled = true)
package org.taoguoguo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

@SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }

}
  1. 编写需要 Secured 注解指定角色访问的控制器
@GetMapping("testSecured")
@Secured({"ROLE_sale","ROLE_admin"})
public String testSecured(){
    return "hello Secured";
}
  1. 在自定义登录逻辑中,为用户分配对应的角色信息

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,ROLE_sale");

@PreAuthorize 进入方法前的权限验证

  1. 开启注解功能 @EnableGlobalMethodSecurity(prePostEnabled = true)
package org.taoguoguo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;

@SpringBootApplication
@MapperScan("org.taoguoguo.mapper")
@EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class SpringSecurityApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }

}
  1. 编写需要 preAuthorize 需要权限验证的控制器
@RequestMapping("/preAuthorize")
@PreAuthorize("hasAuthority('menu:system')")
public String preAuthorize(){
    return "Hello preAuthorize";
}
  1. 在自定义登录逻辑中,为用户分配对应的角色信息

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("manager,menu:system,menu:create");

@PostAuthorize 在方法执行后再进行权限验证,适合验证带有返回值的权限

用法和 preAuthorize 基本一致,比较简单,这边就不详细说明了。重点明白什么场景下使用即可

@PostFilter 权限验证之后对数据进行过滤

留下用户名是 admin1 的数据 表达式中的 filterObject 引用的是方法返回值 List 中的某一个元素

@RequestMapping("getAll")
@PreAuthorize("hasRole('ROLE_ 管理员')")
@PostFilter("filterObject.username == 'admin1'")
@ResponseBody
public List<UserInfo> getAllUser(){
ArrayList<UserInfo> list = new ArrayList<>();
list.add(new UserInfo(1l,"admin1","6666"));
list.add(new UserInfo(2l,"admin2","888"));
return list;
}

@PreFilter 进入控制器之前对数据进行过滤

留下传入参数 id 能对 2 整除的参数数据

@RequestMapping("getTestPreFilter")
@PreAuthorize("hasRole('ROLE_ 管理员')")
@PreFilter(value = "filterObject.id%2==0")
@ResponseBody
public  List<UserInfo>  getTestPreFilter(@RequestBody  List<UserInfo> list){
    list.forEach(t-> {
        System.out.println(t.getId()+"\t"+t.getUsername());
    });
    return list;
}

Spring Security 实现 RememberMe

用户流程及框架实现原理

具体实现方式

  1. 创建表,这个表也可以由程序自动创建
CREATE TABLE `persistent_logins` (
  `username` varchar(64) NOT NULL,
  `series` varchar(64) NOT NULL,
  `token` varchar(64) NOT NULL,
  `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  1. 添加数据库配置文件
#数据库配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/security_db?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
  1. 修改配置类 SecurityConfig 中 注入数据源及配置数据库操作对象
//注入数据源
@Autowired
private DataSource dataSource;

//注入数据源 配置操作数据库对象
@Bean
public PersistentTokenRepository persistentTokenRepository(){
    JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
    jdbcTokenRepository.setDataSource(dataSource);
    //jdbcTokenRepository.setCreateTableOnStartup(true);  //配置此配置则会自动帮我们建表
    return jdbcTokenRepository;
}
  1. 开启 Remeber me 功能
//开启记住我功能
http.rememberMe().tokenRepository(persistentTokenRepository())
    .tokenValiditySeconds(60*15)    //有效时长 15分钟
    .userDetailsService(userDetailsService);
  1. login.html 页面增加记住我 功能标签 【注意:name 属性值必须位 remember-me.不能改为其他值】
<form action="/user/login" method="post">
    用户名:<input type="text" name="username"><br/>
    密 码:<input type="password" name="password"><br/>
    <input type="checkbox" name="remember-me" title="记住密码">自动登录<br/>
    <input type="submit" value="login">
</form>

最后附上完整的配置类代码

package org.taoguoguo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @author taoGuoGuo
 * @description SecurityConfig
 * @website https://www.cnblogs.com/doondo
 * @create 2021-06-11 15:14
 * SpringSecurity 自定义配置
 */
@Configuration
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    //注入数据源
    @Autowired
    private DataSource dataSource;

    //注入数据源 配置操作数据库对象
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //jdbcTokenRepository.setCreateTableOnStartup(true);  //配置此配置则会自动帮我们建表
        return jdbcTokenRepository;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //设置自定义的数据库实现及密码解析器
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单认证
        http.formLogin()    //自定义自己编写登录页面
                .loginPage("/login.html")           //登录页面设置
                .loginProcessingUrl("/user/login")  //登录访问路径
                .defaultSuccessUrl("/sys/loginSuccess")   //登录成功后,跳转路径
                .permitAll()
                .and().authorizeRequests()  //定义请求路径访问规则
                .antMatchers("/","/test/hello","/user/login").permitAll() //设置不需要认证可以直接访问的路径
                //1 hasAuthority方法 具备admin权限才能访问 /test/index资源
                // .antMatchers("/test/index").hasAuthority("admin")
                //2 hasAnyAuthority方法 具备admin,manager其中任一权限 才能访问/test/index资源
                // .antMatchers("/test/index").hasAnyAuthority("admin,manager")
                .antMatchers("/test/index").hasRole("manager")
                .anyRequest().authenticated();   //除此之外任何请求都需要认证

        //开启记住我功能
        http.rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60*15)    //有效时长 15分钟
                .userDetailsService(userDetailsService);

        //关闭csrf防护
        http.csrf().disable();
        //用户注销配置
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/sys/logout").permitAll();
        //自定义403页面
        http.exceptionHandling().accessDeniedPage("/sys/unauth403");
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

相关文章