> 文章列表 > Spring Security 学习笔记 上

Spring Security 学习笔记 上

Spring Security 学习笔记 上

Spring Security 学习笔记

文章目录

  • Spring Security 学习笔记
    • 一、前置知识
    • 二、工程简介
      • 2.1 第一步 创建springboot 工程
      • 2.2 第二步 引入相关依赖
      • 2.3 第三步 编写 controller 进行测试
    • 三、SpringSecurity
      • 3.1 Spring Security 和 Shiro(Apache 旗下的轻量级权限控制框架)
      • 3.2 总结:
  • 四、SpringSecurity 基本原理 —— SpringSecurity 本质是一个过滤器链
    • 4.1 重点三个过滤器:
      • 4.1.1 FilterSecurityInterceptor:是一个方法级的权限过滤器, 基本位于过滤链的最底部。
      • 4.1.2 ExceptionTranslationFilter:是个异常过滤器,用来处理在认证授权过程中抛出的异常
      • 4.1.3 UsernamePasswordAuthenticationFilter:对/login 的 POST 请求做拦截,校验表单中用户名,密码。
    • 4.2 过滤器如进行加载的?
    • 4.3 两个重要接口
      • 4.3 UserDetailsService 接口讲解
        • 4.3.1 实现自定义逻辑控制认证逻辑:
      • 4.4 PasswordEncoder 接口讲解(密码加密)
        • 4.4.1 BCryptPasswordEncoder
    • 5.1 Web权限方案
      • 5.1.1 设置登陆的用户名和密码(三种方法)
        • 5.1.1.1 第一种:配置文件 配置用户名和密码
        • 5.1.1.2 第二种:配置类 配置用户名和密码
        • 5.1.1.3 第三种:自定义编写实现类 配置用户名和密码 (现实开发最常用)
          • a. 编写新的 `SecurityConfig`,设置使用哪个userService实现类
          • b. 编写实现类,返回User对象,User对象用户名密码和操作权限
      • 5.1.2 实现数据库认证来完成用户登录 ()
        • 5.1.2.1 引入`MybatisPlus` 依赖
        • 5.1.2.2 创建表
        • 5.1.2.3 创建实体类
        • 5.1.2.4 创建接口`mapper`
        • 5.1.2.5 编写`UserDetailsService`实现类
        • 5.1.2.6 启动类上加上注解`@MapperScan(参数:包的路径)`
        • 5.1.2.7 `application.properties`配置文件中配置数据库配置
        • 5.1.2.8 `SecurityConfig`,设置userService实现类,登录认证自定义登录页面
          • a. 编写登录页面
          • b. 编写登录成功跳转页面
          • c. controller
          • d. 编写`SecurityConfig`
          • e.测试
      • 5.1.3 用户授权
        • 5.1.3.1 hasAuthority 方法 (针对某一个用户操作)
        • 5.1.3.2 hasAnyAuthority 方法(针对多个用户操作)
        • 5.1.3.3 hasRole 方法
        • 5.1.3.4 hasAnyRole方法
        • 5.1.3.5 自定义403页面
        • 5.1.4 注解使用
          • 5.1.4.1 `@Secured`
            • a. 使用注解先要开启注解功能!
            • b. 在控制器方法上添加注解
            • c. 将角色改为 @Secured({"ROLE_normal","ROLE_管理员"})的角色,即可访问
          • 5.1.4.2 `@PreAuthorize`
            • a. 先开启注解功能:
            • b. 在控制器方法上添加注解
          • 5.1.4.3 `@PostAuthorize`
            • a.先开启注解功能:
            • b. 在控制器方法上添加注解
            • c. 将角色改为 admin 而不是 admins
          • d。测试
          • 5.1.4.4 `@PostFilter`
          • 5.1.4.5 `@PreFilter`
        • 5.1.4 用户注销
        • 配置类
            • 测试
          • 编写成功页面
          • 修改配置文件
          • 测试
        • 基于数据库自动登陆 (关闭网站,再次打开时不需要登陆)
        • 实现原理
          • 认证请求
          • 认证成功后 访问
          • 登陆成功后
          • 生成token
          • 插入数据库
            • 再次经过下一个过滤器
        • 具体实现
            • 第一步 创建数据库表 (可以自动创建)
          • 第二步 修改配置类 注入数据源、配置操作数据库对象
          • 第三步 配置类配置自动登录
          • 第四步 在登录页面添加复位键
          • 测试
        • CSRF
          • 注释掉:
        • 配置类全部


springsecurity

一、前置知识

  1. 掌握Spring框架
  2. 掌握SpringBoot使用
  3. 掌握JavaWeb技术

二、工程简介

springsecurity

2.1 第一步 创建springboot 工程

springsecurity
springsecurity
springsecurity

注意:pom.xml文件改下版本(看个人情况)

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.0</version><relativePath/> <!-- lookup parent from repository -->
</parent>

2.2 第二步 引入相关依赖

<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>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>
</dependencies>

2.3 第三步 编写 controller 进行测试

package com.test.securitydemo1.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("hello")public String hello(){return "hello security";}}

编写application.properties配置文件

# 应用名称
spring.application.name=springsecurity
server.port=8111

springsecurity

发现需要登录,证明Spring Security 已经启用!!!

springsecurity

需要填写运行时,给的密码:用户名是user
springsecurity
登录成功
在这里插入图片描述

三、SpringSecurity

   Spring 是非常流行和成功的 Java 应用开发框架,Spring Security 正是 Spring 家族中的成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
“认证”和“授权”(或者访问控制)是关于安全方面的两个主要区域,一般来说,Web 应用的安全性包括**用户认证(Authentication)用户授权(Authorization)**两个部分,这两点也是 Spring Security 重要核心功能。

  • (1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。通俗点说就是系统认为用户是否能登录。
  • (2)用户授权指的是:验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。通俗点讲就是系统判断用户是否有权限去做某些事情。

官网:SpringSecurity 官网

3.1 Spring Security 和 Shiro(Apache 旗下的轻量级权限控制框架)

Spring Security Shiro
和 Spring 无缝整合 轻量级。Shiro 主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
全面的权限控制 通用性:**好处:**不局限于 Web 环境,可以脱离 Web 环境使用。**缺陷:**在 Web 环境下一些特定的需求需要手动编写代码定制
专门为 Web 开发而设计:旧版本不能脱离 Web 环境使用。新版本对整个框架进行了分层抽取,分成了核心模块和 Web 模块。单独引入核心模块就可以脱离 Web 环境。
重量级
在这里插入图片描述 在这里插入图片描述

3.2 总结:

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

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

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

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

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

SpringSecurity 核心模块:

在这里插入图片描述

四、SpringSecurity 基本原理 —— SpringSecurity 本质是一个过滤器链

从启动是可以获取到过滤器链:

org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
org.springframework.security.web.context.SecurityContextPersistenceFilter 
org.springframework.security.web.header.HeaderWriterFilter
org.springframework.security.web.csrf.CsrfFilter
org.springframework.security.web.authentication.logout.LogoutFilter 
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter 
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter 
org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
org.springframework.security.web.savedrequest.RequestCacheAwareFilter
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
org.springframework.security.web.authentication.AnonymousAuthenticationFilter 
org.springframework.security.web.session.SessionManagementFilter 
org.springframework.security.web.access.ExceptionTranslationFilter 
org.springframework.security.web.access.intercept.FilterSecurityInterceptor

4.1 重点三个过滤器:

4.1.1 FilterSecurityInterceptor:是一个方法级的权限过滤器, 基本位于过滤链的最底部。

部分源码:

public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { //实现Filter方法,是过滤器private static final String FILTER_APPLIED = "__spring_security_filterSecurityInterceptor_filterApplied";private FilterInvocationSecurityMetadataSource securityMetadataSource;private boolean observeOncePerRequest = true;public void init(FilterConfig arg0) { // 初始化}public void destroy() { // 销毁}// 真正过滤方法public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {this.invoke(new FilterInvocation(request, response, chain)); //传入 request response 和 chain(放行操作) }// 执行方法public void invoke(FilterInvocation filterInvocation) throws IOException, ServletException {if (this.isApplied(filterInvocation) && this.observeOncePerRequest) {filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());} else {if (filterInvocation.getRequest() != null && this.observeOncePerRequest) {filterInvocation.getRequest().setAttribute("__spring_security_filterSecurityInterceptor_filterApplied", Boolean.TRUE);}InterceptorStatusToken token = super.beforeInvocation(filterInvocation); // 查看之前过滤器是否已经放行,如放行继续以下操作try {filterInvocation.getChain().doFilter(filterInvocation.getRequest(), filterInvocation.getResponse());} finally {super.finallyInvocation(token);}super.afterInvocation(token, (Object) null);}}
}

4.1.2 ExceptionTranslationFilter:是个异常过滤器,用来处理在认证授权过程中抛出的异常

部分源码:

public class ExceptionTranslationFilter extends GenericFilterBean implements MessageSourceAware {//根据不同的异常做出不同的方案private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws IOException, ServletException {try {chain.doFilter(request, response);} catch (IOException ex) {throw ex;} catch (Exception ex) {// Try to extract a SpringSecurityException from the stacktraceThrowable[] causeChain = this.throwableAnalyzer.determineCauseChain(ex);RuntimeException securityException = (AuthenticationException) this.throwableAnalyzer.getFirstThrowableOfType(AuthenticationException.class, causeChain);if (securityException == null) {securityException = (AccessDeniedException) this.throwableAnalyzer.getFirstThrowableOfType(AccessDeniedException.class, causeChain);}if (securityException == null) {rethrow(ex);}if (response.isCommitted()) {throw new ServletException("Unable to handle the Spring Security Exception "+ "because the response is already committed.", ex);}handleSpringSecurityException(request, response, chain, securityException);}}
}

4.1.3 UsernamePasswordAuthenticationFilter:对/login 的 POST 请求做拦截,校验表单中用户名,密码。

部分源码:

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {//是否是POST请求,得到用户密码:@Overridepublic Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)throws AuthenticationException {if (this.postOnly && !request.getMethod().equals("POST")) {throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());}String username = obtainUsername(request);username = (username != null) ? username.trim() : "";String password = obtainPassword(request);password = (password != null) ? password: "" ;UsernamePasswordAuthenticationToken authRequest = UsernamePasswordAuthenticationToken.unauthenticated(username,password);// Allow subclasses to set the "details" propertysetDetails(request, authRequest);return this.getAuthenticationManager().authenticate(authRequest);}
}

4.2 过滤器如进行加载的?

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

1、 使用SpringSecurity 配置过滤器

  • DelegatingFilterProxy 配置

DelegatingFilterProxy 部分源码

public class DelegatingFilterProxy extends GenericFilterBean {public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {Filter delegateToUse = this.delegate;if (delegateToUse == null) {synchronized(this.delegateMonitor) {delegateToUse = this.delegate;if (delegateToUse == null) {WebApplicationContext wac = this.findWebApplicationContext();if (wac == null) {throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener or DispatcherServlet registered?");}delegateToUse = this.initDelegate(wac); // 初始化}this.delegate = delegateToUse;}}this.invokeDelegate(delegateToUse, request, response, filterChain);}protected Filter initDelegate(WebApplicationContext wac) throws ServletException {String targetBeanName = this.getTargetBeanName();Assert.state(targetBeanName != null, "No target bean name set");Filter delegate = (Filter)wac.getBean(targetBeanName, Filter.class); // 得到一个过滤器 FilterChainProxyif (this.isTargetFilterLifecycle()) {delegate.init(this.getFilterConfig());}return delegate;}
}

FilterChainProxy部分源码:

public class FilterChainProxy extends GenericFilterBean {@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;if (!clearContext) {doFilterInternal(request, response, chain);return;}try {request.setAttribute(FILTER_APPLIED, Boolean.TRUE);doFilterInternal(request, response, chain); // 执行方法}catch (RequestRejectedException ex) {this.requestRejectedHandler.handle((HttpServletRequest) request, (HttpServletResponse) response, ex);}finally {SecurityContextHolder.clearContext();request.removeAttribute(FILTER_APPLIED);}}private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException {FirewalledRequest firewallRequest = this.firewall.getFirewalledRequest((HttpServletRequest) request);HttpServletResponse firewallResponse = this.firewall.getFirewalledResponse((HttpServletResponse) response);List<Filter> filters = getFilters(firewallRequest); //要进行加载的过滤器if (filters == null || filters.size() == 0) {if (logger.isTraceEnabled()) {logger.trace(LogMessage.of(() -> "No security for " + requestLine(firewallRequest)));}firewallRequest.reset();chain.doFilter(firewallRequest, firewallResponse);return;}if (logger.isDebugEnabled()) {logger.debug(LogMessage.of(() -> "Securing " + requestLine(firewallRequest)));}VirtualFilterChain virtualFilterChain = new VirtualFilterChain(firewallRequest, chain, filters);virtualFilterChain.doFilter(firewallRequest, firewallResponse);}//getFilters 方法 一个个加载过滤器private List<Filter> getFilters(HttpServletRequest request) {int count = 0;for (SecurityFilterChain chain : this.filterChains) {if (logger.isTraceEnabled()) {logger.trace(LogMessage.format("Trying to match request against %s (%d/%d)", chain, ++count,this.filterChains.size()));}if (chain.matches(request)) {return chain.getFilters();}}return null;}
}

4.3 两个重要接口

用于自定义开发,例如:查询数据库密码

  • UserDetailsService
  • PasswordEncoder

4.3 UserDetailsService 接口讲解

  当什么也没有配置的时候,账号和密码是由 Spring Security 定义生成的。而在实际项目中账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。

4.3.1 实现自定义逻辑控制认证逻辑:

写一个类继承UsernamePasswordAuthenticationFilter,重写attemptAuthentication方法、父类AbstractAuthenticationProcessingFiltersuccessfulAuthentication成功后执行方法、unsuccessfulAuthentication登陆失败后执行方法 UsernamePasswordAuthenticationFilter的父类是AbstractAuthenticationProcessingFilter

public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {}

如果需要自定义逻辑时(查数据库用户名和密码的方法),需要实现 UserDetailsService 接口即可,返回值 UserDetails。接口定义如下:

public interface UserDetailsService {UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;}

UserDetails 这个类是系统默认的用户 主体

package org.springframework.security.core.userdetails;import java.io.Serializable;
import java.util.Collection;import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;public interface UserDetails extends Serializable {// 表示获取登录用户所有权限/*** Returns the authorities granted to the user. Cannot return <code>null</code>.* @return the authorities, sorted by natural key (never <code>null</code>)*/Collection<? extends GrantedAuthority> getAuthorities();// 表示获取密码/*** Returns the password used to authenticate the user.* @return the password*/String getPassword();// 表示获取用户名/*** Returns the username used to authenticate the user. Cannot return* <code>null</code>.* @return the username (never <code>null</code>)*/String getUsername();// 表示判断账户是否过期/*** Indicates whether the user's account has expired. An expired account cannot be* authenticated.* @return <code>true</code> if the user's account is valid (ie non-expired),* <code>false</code> if no longer valid (ie expired)*/boolean isAccountNonExpired();// 表示判断账户是否被锁定/*** Indicates whether the user is locked or unlocked. A locked user cannot be* authenticated.* @return <code>true</code> if the user is not locked, <code>false</code> otherwise*/boolean isAccountNonLocked();// 表示凭证{密码}是否过期/*** Indicates whether the user's credentials (password) has expired. Expired* credentials prevent authentication.* @return <code>true</code> if the user's credentials are valid (ie non-expired),* <code>false</code> if no longer valid (ie expired)*/boolean isCredentialsNonExpired();// 表示当前用户是否可用/*** Indicates whether the user is enabled or disabled. A disabled user cannot be* authenticated.* @return <code>true</code> if the user is enabled, <code>false</code> otherwise*/boolean isEnabled();}

4.4 PasswordEncoder 接口讲解(密码加密)

package org.springframework.security.crypto.password;public interface PasswordEncoder {// 表示把参数按照特定的解析规则进行解析String encode(CharSequence rawPassword);/*** 表示验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹配,* 则返回 true;如果不匹配,则返回 false。第一个参数表示需要被解析的密码。第二个* 参数表示存储的密码。*/boolean matches(CharSequence rawPassword, String encodedPassword);// 表示如果解析的密码能够再次进行解析且达到更安全的结果则返回 true,否则返回false。默认返回 false。default boolean upgradeEncoding(String encodedPassword) {return false;}}

4.4.1 BCryptPasswordEncoder

BCryptPasswordEncoder 是 Spring Security 官方推荐的密码解析器,平时多使用这个解析器。
BCryptPasswordEncoder 是对 bcrypt 强散列方法的具体实现。是基于 Hash 算法实现的单向加密。可以通过 strength 控制加密强度,默认 10。

BCryptPasswordEncoder源码定义,该类实现了PasswordEncoder的方法:

public class BCryptPasswordEncoder implements PasswordEncoder {// 该类实现了PasswordEncoder的方法
}

举例实现方法:

@Test
public void test01(){// 创建密码解析器BCryptPasswordEncoder bCryptPasswordEncoder = newBCryptPasswordEncoder();// 对密码进行加密String atguigu = bCryptPasswordEncoder.encode("atguigu");// 打印加密之后的数据System.out.println("加密之后数据:\\t"+atguigu);//判断原字符加密后和加密之前是否匹配boolean result = bCryptPasswordEncoder.matches("atguigu", atguigu);// 打印比较结果System.out.println("比较结果:\\t"+result);
}

5.1 Web权限方案

springsecurity

5.1.1 设置登陆的用户名和密码(三种方法)

5.1.1.1 第一种:配置文件 配置用户名和密码

application.properties

spring.security.users.name=admin
spring.security.users.password=admin

此时没有自动生成密码了!!!
springsecurity

登陆成功
springsecurity

5.1.1.2 第二种:配置类 配置用户名和密码

编写 SecurityConfig

package com.test.securitydemo1.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;@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {  //需要继承@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {// 加密接口BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); String password = passwordEncoder.encode("123");//inMemoryAuthentication() 放入内存//withUser 用户名//password 密码//roles 角色auth.inMemoryAuthentication().withUser("admin").password(password).roles("admin"); }//创建PasswordEncoder对象(接口),否则会报空指针异常@BeanPasswordEncoder password(){return new BCryptPasswordEncoder();}
}

注意:需要创建PasswordEncoder对象(该对象是一个接口)!
否则报空指针异常!!!
springsecurity

5.1.1.3 第三种:自定义编写实现类 配置用户名和密码 (现实开发最常用)

注意要把之前的代码注释掉!
步骤:

  1. 编写配置类,设置使用哪个userDetailsService实现类
  2. 编写实现类,返回User对象,User对象用户名密码和操作权限
a. 编写新的 SecurityConfig,设置使用哪个userService实现类
package com.test.securitydemo1.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 javax.sql.DataSource;@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(password());}@BeanPasswordEncoder password(){return new BCryptPasswordEncoder();}
}
b. 编写实现类,返回User对象,User对象用户名密码和操作权限

创建 MyUserDetailsService 实现

package com.test.securitydemo1.service;import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;import java.util.List;@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role"); //授权给角色// 还没连数据库,授权不能为空,角色是个Collection集合,所以传入一个Listreturn new User("mary",new BCryptPasswordEncoder().encode("123"),auths);}
}

5.1.2 实现数据库认证来完成用户登录 ()

springsecurity

5.1.2.1 引入MybatisPlus 依赖

    <dependencies><!--mybatis-plus--><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.1</version></dependency><!--mysql--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><!--lombok 用来简化实体类--><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies>

5.1.2.2 创建表

CREATE TABLE `user_springsecurity` (`id` varchar(32) NOT NULL,`username` varchar(50) NOT NULL,`password` varchar(50) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表';

5.1.2.3 创建实体类

package com.test.securitydemo1.entity;import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;@Data //自动生成,get,set,构建方法等方法构建
@TableName("user_springsecurity")
public class Users {private String id;@TableField("username")private String userName;@TableField("password")private String password;}

5.1.2.4 创建接口mapper

package com.test.securitydemo1.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.test.securitydemo1.entity.Users;
import org.springframework.stereotype.Repository;@Repository //注意要加上注解
public interface UserMapper extends BaseMapper<Users> { //BaseMapper 把增删改查都构建了}

5.1.2.5 编写UserDetailsService实现类

package com.test.securitydemo1.service;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.securitydemo1.entity.Users;
import com.test.securitydemo1.mapper.UserMapper;
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.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;import java.util.List;@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {@Autowiredprivate UserMapper userMapper; //注入mapper@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //输入用户名、密码后先到这里,运行loadUserByUsername方法//调用userMapper方法查询数据库,根据用户名去查数据库//QueryWrapper条件构造器QueryWrapper<Users> wrapper = new QueryWrapper<Users>();//where username = ?wrapper.eq("username",username);//得到某一条记录Users users = userMapper.selectOne(wrapper);//数据库没有用户名,认证失败if (users == null ){throw  new UsernameNotFoundException("用户名不存在!");}List<GrantedAuthority> auths =AuthorityUtils.commaSeparatedStringToAuthorityList("role");//查询数据库返回users对象,得到用户名和密码。返回return new User(users.getUserName(),new BCryptPasswordEncoder().encode(users.getPassword()),auths);}
}

5.1.2.6 启动类上加上注解@MapperScan(参数:包的路径)

package com.test.securitydemo1;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("com.test.securitydemo1.mapper")
public class SpringsecurityApplication {public static void main(String[] args) {SpringApplication.run(SpringsecurityApplication.class, args);}}

5.1.2.7 application.properties配置文件中配置数据库配置

#mysql数据库连接 此时是mysql8版本
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dblearning?serverTimezone=GMT%2B8&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

5.1.2.8 SecurityConfig,设置userService实现类,登录认证自定义登录页面

springsecurity

a. 编写登录页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><form action="/user/login" method="post">用户名:<input type="test" name="username"> <!--必须要叫这个名字--><br/>密码:<input type="test" name="password"><!--必须要叫这个名字--><br/><input type="checkbox" name="remember-me"/>自动登录<br/><input type="submit" value="login"></form>
</body>
</html>

注意:传的值必须是usernamepassword

源码中: 在UsernamePasswordAuthenticationFilter过滤器中,

springsecurity
springsecurity
springsecurity

b. 编写登录成功跳转页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
登陆成功
<a href="/logout">退出</a>
</body>
</html>
c. controller
package com.test.securitydemo1.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("hello")public String hello(){return "hello security";}@GetMapping("index")public String index(){return "hello index";}
}
d. 编写SecurityConfig
package com.test.securitydemo1.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 javax.sql.DataSource;@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(password());}@Overrideprotected void configure(HttpSecurity http) throws Exception {//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");//退出http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证.anyRequest().authenticated()//所有请求都可以访问.and().csrf().disable(); //关闭csrf防护}@BeanPasswordEncoder password(){return new BCryptPasswordEncoder();}
}
e.测试

springsecurity
访问: localhost:8111/test/index跳转到localhost:8111/test/login
springsecurity

登陆成功
springsecurity

5.1.3 用户授权

springsecurity

5.1.3.1 hasAuthority 方法 (针对某一个用户操作)

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

给用户登录主体赋予权限:

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins");
    @Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法.antMatchers("/test/index").hasAuthority("admins").anyRequest().authenticated()//所有请求都可以访问.userDetailsService(userDetailsService).and().csrf().disable(); //关闭csrf防护}

当没有权限,系统返回403
springsecurity

5.1.3.2 hasAnyAuthority 方法(针对多个用户操作)

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

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

springsecurity

    @Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//2. hasAnyAuthority.antMatchers("/test/index").hasAnyAuthority("admins","manager") //满足其中某一个.anyRequest().authenticated()//所有请求都可以访问.userDetailsService(userDetailsService).and().csrf().disable(); //关闭csrf防护}

5.1.3.3 hasRole 方法

如果用户具备给定角色就允许访问,否则出现 403。如果当前主体具有指定的角色,则返回 true。

源码中AuthorizeHttpRequestsConfigurer调用 AuthorityAuthorizationManager
springsecurity

hasRole中角色有相关方法有ROLE_前缀
springsecurity

编写SecurityConfig

    @Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//3. hasRole方法.antMatchers("/test/index").hasRole("sale").anyRequest().authenticated()//所有请求都可以访问.userDetailsService(userDetailsService).and().csrf().disable(); //关闭csrf防护}

5.1.3.4 hasAnyRole方法

表示用户具备任何一个条件都可以访问。

编写SecurityConfig

    @Overrideprotected void configure(HttpSecurity http) throws Exception {http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//4. hasAnyRole方法.antMatchers("test/index").hasAnyRole("sale","manager").anyRequest().authenticated()//所有请求都可以访问.userDetailsService(userDetailsService).and().csrf().disable(); //关闭csrf防护}

5.1.3.5 自定义403页面

springsecurity

编写SecurityConfig

    @Overrideprotected void configure(HttpSecurity http) throws Exception {//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/test/index").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法//.antMatchers("/test/index").hasAuthority("admins")//2. hasAnyAuthority//.antMatchers("/test/index").hasAnyAuthority("admins","manager")//3. hasRole方法.antMatchers("/test/index").hasRole("sale")//4. hasAnyRole方法//.antMatchers("test/index").hasAnyRole("sale","manager").anyRequest().authenticated()//所有请求都可以访问.and().csrf().disable(); //关闭csrf防护}

有权限:
springsecurity

无权限:
springsecurity

5.1.4 注解使用

springsecurity

5.1.4.1 @Secured

判断用户是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“。

a. 使用注解先要开启注解功能!

@EnableGlobalMethodSecurity(securedEnabled=true)

package com.test.securitydemo1;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("com.test.securitydemo1.mapper")
@EnableGlobalMethodSecurity(securedEnabled=true)
public class SpringsecurityApplication {public static void main(String[] args) {SpringApplication.run(SpringsecurityApplication.class, args);}}
b. 在控制器方法上添加注解
package com.test.securitydemo1.controller;import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("update")@Secured({"ROLE_sale","ROLE_manager"})  //只有这种ROLE_sale,ROLE_manager角色才能访问public String update(){return "hello update";}}
c. 将角色改为 @Secured({“ROLE_normal”,“ROLE_管理员”})的角色,即可访问

MyUserDetailsService,编写UserDetailsService实现类中:

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admins,ROLE_sale");
5.1.4.2 @PreAuthorize
a. 先开启注解功能:

@EnableGlobalMethodSecurity(prePostEnabled = true)

b. 在控制器方法上添加注解

@PreAuthorize:注解适合进入方法前的权限验证, @PreAuthorize 可以将登录用户的 roles/permissions 参数传到方法中。

package com.test.securitydemo1.controller;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("update")@PreAuthorize("hasAnyAuthority('admins')")public String update(){return "hello update";}
}
5.1.4.3 @PostAuthorize
a.先开启注解功能:

@EnableGlobalMethodSecurity(prePostEnabled = true)

b. 在控制器方法上添加注解

@PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值的权限.

package com.test.securitydemo1.controller;import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("update")@PostAuthorize("hasAnyAuthority('admins')")public String update(){System.out.println("update...");return "hello update";}
}
c. 将角色改为 admin 而不是 admins

MyUserDetailsService,编写UserDetailsService实现类中:

List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
d。测试

使用admin访问:
springsecurity

但是没有访问权限:
springsecurity

5.1.4.4 @PostFilter

@PostFilter :方法返回数据进行过滤。权限验证之后对数据进行过滤留下用户名是 admin1 的数据,表达式中的 filterObject 引用的是方法返回值 List 中的某一个元素

@GetMapping("getAll")
@PostAuthorize("hasAnyAuthority('admin')")
@PostFilter("filterObject.userName.equals('admin1')") //返回数据进行过滤
public List<Users> getAllUser(){ArrayList<Users> list = new ArrayList<>();list.add(new Users("11","admin1","6666"));list.add(new Users("21","admin2","888"));return list;
}

注意修改一下实体类,加俩注解:

package com.test.securitydemo1.entity;import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@TableName("user_springsecurity")
@AllArgsConstructor //有参数构造方法
@NoArgsConstructor //无参数构造方法
public class Users {private String id;@TableField("username")private String userName;@TableField("password")private String password;
}

测试:

注意要有注解:
@EnableGlobalMethodSecurity(prePostEnabled = true)

此时只返回了一条数据:
springsecurity

5.1.4.5 @PreFilter

@PreFilter: 进入控制器之前对数据(传入数据)进行过滤

注意要有注解:
@EnableGlobalMethodSecurity(prePostEnabled = true)

@PostMapping("getTestPreFilter")
@PreAuthorize("hasRole('ROLE_sale')")
@PreFilter(value = "filterObject.userName.equals('aaa')")
public List<Users> getTestPreFilter(@RequestBody List<Users> list){list.forEach(t-> {System.out.println(t.getId()+"\\t"+t.getUserName());});return list;
}

测试:
加入cookie
springsecurity
测试只返回一条数据
springsecurity

5.1.4 用户注销

配置类

    //退出 .logoutUrl 退出路径     logoutSuccessUrl退出后跳转到哪里http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();
测试
  1. 修改配置类,登陆成功后跳转到成功页面
  2. 在成功页面添加超链接写设置退出路径
  3. 登陆成功后,在成功页面点击退出,在去访问其他controller不能进行访问
编写成功页面
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
登陆成功
<a href="/logout">退出</a>
</body>
</html>
修改配置文件
    @Overrideprotected void configure(HttpSecurity http) throws Exception {//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");//退出 .logoutUrl 退出路径     logoutSuccessUrl退出后跳转到哪里http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/success.html").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法//.antMatchers("/test/index").hasAuthority("admins")//2. hasAnyAuthority//.antMatchers("/test/index").hasAnyAuthority("admins","manager")//3. hasRole方法.antMatchers("/test/index").hasRole("sale")//4. hasAnyRole方法//.antMatchers("test/index").hasAnyRole("sale","manager").and().csrf().disable(); //关闭csrf防护}
测试

访问登录页面:
springsecurity

登陆成功,之后点击退出,应该再次访问成功页面跳转回登陆页面。需要登陆!
springsecurity
springsecurity

基于数据库自动登陆 (关闭网站,再次打开时不需要登陆)

  1. cookie
  2. 安全框架实现自动登录

springsecurity
springsecurity

实现原理

认证请求

UsernamePasswordAuthenticationFilter
springsecurity

认证成功后 访问

AbstractAuthenticationProcessingFilter successfulAuthentication

登陆成功后

AbstractAuthenticationProcessingFilter loginSuccess

生成token

rememberMeServices 实现类 PersistentTokenBasedRememberMeServices onLoginSuccess
springsecurity

插入数据库

rememberMeServices 实现类 PersistentTokenBasedRememberMeServices 调用 tokenRepository.createNewToken

springsecurity

JdbcTokenRepositoryImpl extends JdbcDaoSupport implements PersistentTokenRepository

JdbcTokenRepositoryImpl
RememberMeToken

含建表语句
springsecurity

再次经过下一个过滤器

RememberMeAuthenticationFilter rememberMeServices.autoLogin

public class RememberMeAuthenticationFilter extends GenericFilterBean implements ApplicationEventPublisherAware {private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws IOException, ServletException {if (SecurityContextHolder.getContext().getAuthentication() != null) {this.logger.debug(LogMessage.of(() -> "SecurityContextHolder not populated with remember-me token, as it already contained: '"+ SecurityContextHolder.getContext().getAuthentication() + "'"));chain.doFilter(request, response);return;}Authentication rememberMeAuth = this.rememberMeServices.autoLogin(request, response);   //自动登录if (rememberMeAuth != null) {// Attempt authenticaton via AuthenticationManagertry {rememberMeAuth = this.authenticationManager.authenticate(rememberMeAuth);// Store to SecurityContextHolderSecurityContext context = SecurityContextHolder.createEmptyContext();context.setAuthentication(rememberMeAuth);SecurityContextHolder.setContext(context);onSuccessfulAuthentication(request, response, rememberMeAuth);this.logger.debug(LogMessage.of(() -> "SecurityContextHolder populated with remember-me token: '"+ SecurityContextHolder.getContext().getAuthentication() + "'"));this.securityContextRepository.saveContext(context, request, response);if (this.eventPublisher != null) {this.eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(SecurityContextHolder.getContext().getAuthentication(), this.getClass()));}if (this.successHandler != null) {this.successHandler.onAuthenticationSuccess(request, response, rememberMeAuth);return;}}catch (AuthenticationException ex) {this.logger.debug(LogMessage.format("SecurityContextHolder not populated with remember-me token, as AuthenticationManager "+ "rejected Authentication returned by RememberMeServices: '%s'; "+ "invalidating remember-me token", rememberMeAuth),ex);this.rememberMeServices.loginFail(request, response);onUnsuccessfulAuthentication(request, response, ex);}}chain.doFilter(request, response);}
}
public abstract class AbstractRememberMeServices
implements RememberMeServices, InitializingBean, LogoutHandler, MessageSourceAware {/*** Template implementation which locates the Spring Security cookie, decodes it into a* delimited array of tokens and submits it to subclasses for processing via the* <tt>processAutoLoginCookie</tt> method.* <p>* The returned username is then used to load the UserDetails object for the user,* which in turn is used to create a valid authentication token.*/@Overridepublic final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {String rememberMeCookie = extractRememberMeCookie(request);if (rememberMeCookie == null) {return null;}this.logger.debug("Remember-me cookie detected");if (rememberMeCookie.length() == 0) {this.logger.debug("Cookie was empty");cancelCookie(request, response);return null;}try {String[] cookieTokens = decodeCookie(rememberMeCookie);   //数据库解密UserDetails user = processAutoLoginCookie(cookieTokens, request, response);this.userDetailsChecker.check(user);  //判断是否自动登录this.logger.debug("Remember-me cookie accepted");return createSuccessfulAuthentication(request, user);}catch (CookieTheftException ex) {cancelCookie(request, response);throw ex;}catch (UsernameNotFoundException ex) {this.logger.debug("Remember-me login was valid but corresponding user not found.", ex);}catch (InvalidCookieException ex) {this.logger.debug("Invalid remember-me cookie: " + ex.getMessage());}catch (AccountStatusException ex) {this.logger.debug("Invalid UserDetails: " + ex.getMessage());}catch (RememberMeAuthenticationException ex) {this.logger.debug(ex.getMessage());}cancelCookie(request, response);return null;}}

userDetailsChecker.check(user); 判断登录
springsecurity

具体实现

第一步 创建数据库表 (可以自动创建)

第二步 修改配置类 注入数据源、配置操作数据库对象

第三步 配置类配置自动登录

第四步 在登录页面添加复位键

第一步 创建数据库表 (可以自动创建)

创建数据库

create table persistent_logins (
username varchar(64) not null,
series varchar(64) primary key,
token varchar(64) not null, 
last_used timestamp not null)
第二步 修改配置类 注入数据源、配置操作数据库对象

SecurityConfigTest

    @Autowiredprivate UserDetailsService userDetailsService;//注入数据源@Autowiredprivate DataSource dataSource;//配置对象@Beanpublic PersistentTokenRepository persistentTokenRepository(){JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();jdbcTokenRepository.setDataSource(dataSource);//jdbcTokenRepository.setCreateTableOnStartup(true);//自动创建表return jdbcTokenRepository;}
第三步 配置类配置自动登录
@Overrideprotected void configure(HttpSecurity http) throws Exception {//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");//退出 .logoutUrl 退出路径     logoutSuccessUrl退出后跳转到哪里http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html") //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.defaultSuccessUrl("/success.html").permitAll() //登录成功后的,跳转路径.and().authorizeHttpRequests() //哪些需要认证.antMatchers("/","/test/hello","/user/login").permitAll() //设置那些路径可以直接访问,不需要直接做认证//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法//.antMatchers("/test/index").hasAuthority("admins")//2. hasAnyAuthority//.antMatchers("/test/index").hasAnyAuthority("admins","manager")//3. hasRole方法.antMatchers("/test/index").hasRole("sale")//4. hasAnyRole方法//.antMatchers("test/index").hasAnyRole("sale","manager").anyRequest().authenticated()//所有请求都可以访问.and().rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(60)//设置有效时长,单位秒.userDetailsService(userDetailsService).and().csrf().disable(); //关闭csrf防护}
第四步 在登录页面添加复位键

注意: 框架需要 name 必须等于 remember-me

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body><form action="/user/login" method="post">用户名:<input type="test" name="username"> <!--必须要叫这个名字--><br/>密码:<input type="test" name="password"><!--必须要叫这个名字--><br/><input type="checkbox" name="remember-me"/>自动登录<br/><input type="submit" value="login"></form>
</body>
</html>
测试

springsecurity

springsecurity

数据库已存入token
springsecurity

重新打开网页,也是可以的
springsecurity

CSRF

跨站请求伪造(英语:Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已登录的 Web 应用程序上执行非本意的操作的攻击方法。跟跨网站脚本(XSS)相比,XSS 利用的是用户对指定网站的信任,CSRF 利用的是网站对用户网页浏览器的信任。

跨站请求攻击,简单地说,是攻击者通过一些技术手段欺骗用户的浏览器去访问一个自己曾经认证过的网站并运行一些操作(如发邮件,发消息,甚至财产操作如转账和购买商品)。由于浏览器曾经认证过,所以被访问的网站会认为是真正的用户操作而去运行。这利用了 web 中用户身份验证的一个漏洞:简单的身份验证只能保证请求发自某个用户的浏览器,却不能保证请求本身是用户自愿发出的。

从 Spring Security 4.0 开始,默认情况下会启用 CSRF 保护,以防止 CSRF 攻击应用程序,Spring Security CSRF 会针对 PATCH,POST,PUT 和 DELETE 方法进行防护。

#####添加依赖

        <!--对Thymeleaf添加Spring Security标签支持--><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId></dependency>
注释掉:
`.and().csrf().disable(); //关闭csrf防护`

添加

<input type="hidden" th:if ="${_csrf}!=null" th:value="$_csrf.token}" name="_csrf"/>
CsrfFilter
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)throws ServletException, IOException {request.setAttribute(HttpServletResponse.class.getName(), response);CsrfToken csrfToken = this.tokenRepository.loadToken(request);boolean missingToken = (csrfToken == null);if (missingToken) {csrfToken = this.tokenRepository.generateToken(request);this.tokenRepository.saveToken(csrfToken, request, response);}request.setAttribute(CsrfToken.class.getName(), csrfToken);request.setAttribute(csrfToken.getParameterName(), csrfToken);if (!this.requireCsrfProtectionMatcher.matches(request)) {if (this.logger.isTraceEnabled()) {this.logger.trace("Did not protect against CSRF since request did not match "+ this.requireCsrfProtectionMatcher);}filterChain.doFilter(request, response);return;}String actualToken = request.getHeader(csrfToken.getHeaderName());if (actualToken == null) {actualToken = request.getParameter(csrfToken.getParameterName());}if (!equalsConstantTime(csrfToken.getToken(), actualToken)) {this.logger.debug(LogMessage.of(() -> "Invalid CSRF token found for " + UrlUtils.buildFullRequestUrl(request)));AccessDeniedException exception = (!missingToken) ? new InvalidCsrfTokenException(csrfToken, actualToken): new MissingCsrfTokenException(actualToken);this.accessDeniedHandler.handle(request, response, exception);return;}filterChain.doFilter(request, response);}
  1. 生成 csrfToken 保存到 HttpSession 或者 Cookie 中

  2. 请求到来时,从请求中提取 csrfToken,和保存的 csrfToken 做比较,进而判断当前请求是否合法。主要通过 CsrfFilter 过滤器来完成。

配置类全部

package com.test.securitydemo1.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;@Configuration
public class SecurityConfigTest extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;//注入数据源@Autowiredprivate DataSource dataSource;//@Beanpublic PersistentTokenRepository persistentTokenRepository(){JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();jdbcTokenRepository.setDataSource(dataSource);//jdbcTokenRepository.setCreateTableOnStartup(true);//自动创建表return jdbcTokenRepository;}@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(password());}@Overrideprotected void configure(HttpSecurity http) throws Exception {//配置url的访问权限http.authorizeRequests() //哪些需要认证.antMatchers("/").permitAll() //设置那些路径可以直接访问,不需要直接做认证.antMatchers("/**update**").permitAll().antMatchers("/login/**").permitAll()//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法//.antMatchers("/test/index").hasAuthority("admins")//2. hasAnyAuthority//.antMatchers("/test/index").hasAnyAuthority("admins","manager")//3. hasRole方法.antMatchers("/test/index").hasRole("sale")//4. hasAnyRole方法//.antMatchers("test/index").hasAnyRole("sale","manager").anyRequest().authenticated();//所有请求都可以访问//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");//退出 .logoutUrl 退出路径     logoutSuccessUrl退出后跳转到哪里http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html").permitAll() //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/success.html") //登录成功后的,跳转路径.failureUrl("/login?error").and().rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(60)//设置有效时长,单位秒.userDetailsService(userDetailsService);//关闭csrf保护功能http.csrf().disable();}@BeanPasswordEncoder password(){return new BCryptPasswordEncoder();}
}
p) throws Exception {//配置url的访问权限http.authorizeRequests() //哪些需要认证.antMatchers("/").permitAll() //设置那些路径可以直接访问,不需要直接做认证.antMatchers("/**update**").permitAll().antMatchers("/login/**").permitAll()//当前登录的用户,只有具有"admins"权限,才能访问这个路径("/test/index")//1. hasAuthority() 方法//.antMatchers("/test/index").hasAuthority("admins")//2. hasAnyAuthority//.antMatchers("/test/index").hasAnyAuthority("admins","manager")//3. hasRole方法.antMatchers("/test/index").hasRole("sale")//4. hasAnyRole方法//.antMatchers("test/index").hasAnyRole("sale","manager").anyRequest().authenticated();//所有请求都可以访问//配置没有权限访问跳转自定义页面http.exceptionHandling().accessDeniedPage("/unauth.html");//退出 .logoutUrl 退出路径     logoutSuccessUrl退出后跳转到哪里http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();http.formLogin() //自定义自己编写自定义页面.loginPage("/login.html").permitAll() //登陆页面设置.loginProcessingUrl("/user/login") //登陆访问的路径.usernameParameter("username").passwordParameter("password").defaultSuccessUrl("/success.html") //登录成功后的,跳转路径.failureUrl("/login?error").and().rememberMe().tokenRepository(persistentTokenRepository()).tokenValiditySeconds(60)//设置有效时长,单位秒.userDetailsService(userDetailsService);//关闭csrf保护功能http.csrf().disable();}@BeanPasswordEncoder password(){return new BCryptPasswordEncoder();}
}