1、引入pom.xml

   <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId><version>2.2.13.RELEASE</version></dependency>

2、配置类主要内容

@Overrideprotected void configure(HttpSecurity http) throws Exception {/*使用token认证  不使用session  禁用CSRF*/http.csrf().disable()/*认证异常处理*/.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()/*不会创建HttpSession*/.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()/*请求白名单*/.authorizeRequests().antMatchers("/auth/**","/login","/getSMSCode","/captchaImage").permitAll().antMatchers(HttpMethod.GET,"/","/*.html","/**/*.html","/**/*.css","/**/*.js","/profile/**").permitAll().antMatchers("/swagger-ui/**").anonymous().antMatchers("/swagger-ui.html").anonymous().antMatchers("/swagger-resources/**").anonymous().antMatchers("/webjars/**").anonymous().antMatchers("/*/api-docs").anonymous().antMatchers("/druid/**").anonymous()/*出去以上请求 全部需要鉴权*/.anyRequest().authenticated().and()/*安全劫持*/.headers().frameOptions().disable();/*退出成功处理*/http.logout().logoutSuccessUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);/* 认证之前检验token */http.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);http.addFilterBefore(corsFilter,JwtAuthenticationTokenFilter.class);http.addFilterBefore(corsFilter, LogoutFilter.class);}/*** 强散列哈希加密实现*/@Beanpublic BCryptPasswordEncoder bCryptPasswordEncoder(){return new BCryptPasswordEncoder();}/*** 身份认证接口*/@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception{auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());//自定义验证auth.authenticationProvider(new MyAuthenticationProvider());}
package com.yoohoo.framework.security.service;import com.yoohoo.common.utils.StringUtils;
import com.yoohoo.common.utils.redis.RedisCache;
import com.yoohoo.common.utils.spring.SpringUtils;
import com.yoohoo.framework.security.sms.SmsCodeAuthenticationToken;
import com.yoohoo.framework.service.TokenService;
import com.yoohoo.system.base.domain.ServiceException;
import com.yoohoo.system.base.util.SecurityUtils;
import com.yoohoo.system.modules.system.domain.SysUser;
import com.yoohoo.system.modules.system.domain.vo.LoginUser;
import com.yoohoo.system.modules.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;@Component
public class MyAuthenticationProvider implements AuthenticationProvider {private SysUserServiceImpl sysUserService = SpringUtils.getBean(SysUserServiceImpl.class);private RedisCache redisCache = SpringUtils.getBean(RedisCache.class);@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String username = authentication.getName();String password = (String) authentication.getCredentials();UserDetails userDeatils = null;SysUser sysUser = null;/*手机号+验证码*/sysUser = sysUserService.selectUserByPhone(username);Object cacheObject = redisCache.getCacheObject("login:" + username);if (password == null){throw new ServiceException("验证码不能为空", 400);}if (StringUtils.isNull(cacheObject)) {throw new ServiceException("验证码已失效", 400);}if (password.equals(cacheObject.toString())) {//认证通过  封装认证之后信息返回userDeatils = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, null);SmsCodeAuthenticationToken result = new SmsCodeAuthenticationToken(userDeatils, userDeatils.getAuthorities());result.setDetails(authentication.getDetails());return result;} else {throw new ServiceException("验证码不匹配", 400);}}@Overridepublic boolean supports(Class<?> authentication) {//被哪种认证方式支持  使用SmsCodeAuthenticationToken  将会进入进行验证return (SmsCodeAuthenticationToken.class.isAssignableFrom(authentication));}
}

3、自定义AuthenticationToken

package com.yoohoo.framework.security.sms;import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.SpringSecurityCoreVersion;import java.util.Collection;/*** 短信登录 AuthenticationToken,模仿 UsernamePasswordAuthenticationToken 实现*/
public class SmsCodeAuthenticationToken extends AbstractAuthenticationToken {private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;/*** 手机号码*/private final Object principal;/*** 验证码*/private Object credentials;/*** 构建一个没有鉴权的 SmsCodeAuthenticationToken*/public SmsCodeAuthenticationToken(Object principal,Object code) {super(null);this.principal = principal;this.credentials = code;setAuthenticated(false);}/*** 构建拥有鉴权的 SmsCodeAuthenticationToken*/public SmsCodeAuthenticationToken(Object principal, Collection<? extends GrantedAuthority> authorities) {super(authorities);this.principal = principal;// must use super, as we overridesuper.setAuthenticated(true);}@Overridepublic Object getCredentials() {return this.credentials;}@Overridepublic Object getPrincipal() {return this.principal;}@Overridepublic void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {if (isAuthenticated) {throw new IllegalArgumentException("Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");}super.setAuthenticated(false);}@Overridepublic void eraseCredentials() {super.eraseCredentials();}
}

4、使用

         if () {//自定义验证方式authenticate = authenticationManager.authenticate(new SmsCodeAuthenticationToken(account, password));} else {//默认验证方式authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(account, password));}

SpringSecurity多种认证方式记录之自定义相关推荐

  1. EntityFramework的多种记录日志方式,记录错误并分析执行时间过长原因

    今天我们来聊聊EF的日志记录. 一个好的数据库操作记录不仅仅可以帮你记录用户的操作, 更应该可以帮助你获得效率低下的语句来帮你提高运行效率 废话不多说,我们开始 环境和相关技术 本文采用的环境与技术 ...

  2. SpringSecurity Oauth2 认证授权(二)springboot快速入门与底层介绍

    集成SpringBoot 快速上手 创建maven工程 导入pom <?xml version="1.0" encoding="UTF-8"?> & ...

  3. Authentication(认证方式)与 Authorization(授权)

    1.Authentication(认证):认证方式现共有8种,可以启用一种或多种认证方式,只要有一种认证方式通过,就不再 进行其它方式的认证.通常启用X509 Client Certs和Service ...

  4. SpringSecurity用户认证设置用户名和密码的三种方式

    文章目录 SpringSecurity用户认证设置用户名和密码的三种方式 首先明白几个单词的意思: SpringSecurity默认的用户认证 1.通过配置文件进行用户认证 2.通过配置类进行用户认证 ...

  5. 看清spring security 认证流程,自定义认证方式

    一.文献参考 Spring Security认证与授权的原理(源码分析,超详细)_Zystem-CSDN博客_springsecurity认证原理 spring security为什么这么复杂? - ...

  6. 源码剖析Django REST framework的认证方式及自定义认证

    源码剖析Django REST framework的认证方式 由Django的CBV模式流程,可以知道在url匹配完成后,会执行自定义的类中的as_view方法. 如果自定义的类中没有定义as_vie ...

  7. ASP.NET Core 自定义认证方式--请求头认证

    Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思路 网关可以做一部分的认证和授权,服务内部有时候也会需要 ...

  8. excel学习笔记:数据格式,单元格格式(快捷键,自动调整行列宽,条件格式,自定义格式,日期星期时间的设置,特殊数字,多种填充方式,从下拉列表选择,数据验证。)

    文章目录 数据格式.单元格格式 1. 快捷键 2. 自动调整列/行宽 3. 条件格式 4. 日期设置 5. 星期设置 6. 时间设置 7. 特殊数字 8. 选中多个填充,ctrl选中,输入100,ct ...

  9. SpringSecurity实战:基于mysql自定义SpringSecurity权限认证规则

    上文<Spring Security 源码分析:Spring Security 授权过程>已经详细分析了Spring Security 授权过程,接下来通过上文的授权过程我们可以自定义授权 ...

  10. SpringSecurity 学习笔记分享 记录历程开篇

    基础翻译篇 官方文档地址 GitHub demo 代码 简介 Spring Security 是一个提供身份验证,授权,保护以及防止常见攻击的框架,由于同时支持响应式和命令式,是spring框架的安全 ...

最新文章

  1. [翻译]一步步教你配置SQL SERVER合并复制(五)配置Publisher(上)
  2. cut最后几位 shell_Linux Shell之cut命令
  3. 基于Django进行简单的微信开发
  4. 在Linux中实现https访问站点
  5. 开始学习C#.Net
  6. 7.EVE-NG硬盘扩容,存储海量镜像
  7. 语音识别在智能交通中的几种应用分析
  8. 背水一战 Windows 10 (42) - 控件(导航类): Frame 动画
  9. ValueError: No JSON object could be decoded?此种异常的解决方案之一
  10. P2770 航空路线问题
  11. 把3000行代码重构成15行的牛逼操作!!!
  12. 蓝桥杯省赛2015年——奇妙的数字
  13. Java蓝桥模拟战——特殊的数字:153是一个非常特殊的数,它等于它的每位数字的立方和,即153=1*1*1+5*5*5+3*3*3。编程求所有满足这种条件的三位十进制数。
  14. Win7升为Win10以及win7系统的重装
  15. h3cr4900g3安装系统_H3C服务器安装Windows操作系统
  16. word表格导出为图像
  17. AUTOSAR开发工具DaVinci Configurator里的Modules
  18. 嵌入式操作系统和RTOS(实时操作系统)介绍。
  19. 下载opencv3.4.2.16
  20. 如何查看python安装了哪些模块_Python模块如何安装 并确认模块已经安装好?

热门文章

  1. 基于局域网网络编程实现开发板显示相册以及视频和音乐
  2. DAOS 分布式异步对象存储|事务模型
  3. 模糊图片怎么变清晰?好用的方法教程来了
  4. 可搜索加密简要介绍与相关概念
  5. 为什么要用谷歌浏览器翻译插件?| 文末福利
  6. 谷歌浏览器翻译插件方便阅读方法,收藏备用
  7. Android Q适配攻略(五)(存储权限变更)
  8. 蓝牙连接测试系统软件,蓝牙测试软件官方版
  9. 海康摄像头之FTP服务器搭建及使用
  10. android的备忘录带闹钟提醒,‎App Store 上的“Reminders 3 - 款带有闹钟提醒功能的备忘录”...