Spring Security Oauth2.0 实现短信验证码登录
时间:2022-04-27
本文章向大家介绍Spring Security Oauth2.0 实现短信验证码登录,主要内容包括spring security oauth2 登录过程详解、定义手机号登录令牌、手机号登录校验逻辑、登录过程filter处理、生产token 位置、配置以上自定义、在spring security 配置 上边定一个的那个聚合配置、使用、源码、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。
spring security oauth2 登录过程详解
定义手机号登录令牌
/**
* @author lengleng
* @date 2018/1/9
* 手机号登录令牌
*/
public class MobileAuthenticationToken extends AbstractAuthenticationToken {
private static final long serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;
private final Object principal;
public MobileAuthenticationToken(String mobile) {
super(null);
this.principal = mobile;
setAuthenticated(false);
}
public MobileAuthenticationToken(Object principal,
Collection<? extends GrantedAuthority> authorities) {
super(authorities);
this.principal = principal;
super.setAuthenticated(true);
}
public Object getPrincipal() {
return this.principal;
}
@Override
public Object getCredentials() {
return null;
}
public 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);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
}
}
手机号登录校验逻辑
/**
* @author lengleng
* @date 2018/1/9
* 手机号登录校验逻辑
*/
public class MobileAuthenticationProvider implements AuthenticationProvider {
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken) authentication;
UserVo userVo = userService.findUserByMobile((String) mobileAuthenticationToken.getPrincipal());
UserDetailsImpl userDetails = buildUserDeatils(userVo);
if (userDetails == null) {
throw new InternalAuthenticationServiceException("手机号不存在:" + mobileAuthenticationToken.getPrincipal());
}
MobileAuthenticationToken authenticationToken = new MobileAuthenticationToken(userDetails, userDetails.getAuthorities());
authenticationToken.setDetails(mobileAuthenticationToken.getDetails());
return authenticationToken;
}
private UserDetailsImpl buildUserDeatils(UserVo userVo) {
return new UserDetailsImpl(userVo);
}
@Override
public boolean supports(Class<?> authentication) {
return MobileAuthenticationToken.class.isAssignableFrom(authentication);
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
登录过程filter处理
**
* @author lengleng
* @date 2018/1/9
* 手机号登录验证filter
*/
public class MobileAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public static final String SPRING_SECURITY_FORM_MOBILE_KEY = "mobile";
private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
private boolean postOnly = true;
public MobileAuthenticationFilter() {
super(new AntPathRequestMatcher(SecurityConstants.MOBILE_TOKEN_URL, "POST"));
}
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals(HttpMethod.POST.name())) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
MobileAuthenticationToken mobileAuthenticationToken = new MobileAuthenticationToken(mobile);
setDetails(request, mobileAuthenticationToken);
return this.getAuthenticationManager().authenticate(mobileAuthenticationToken);
}
protected String obtainMobile(HttpServletRequest request) {
return request.getParameter(mobileParameter);
}
protected void setDetails(HttpServletRequest request,
MobileAuthenticationToken authRequest) {
authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public String getMobileParameter() {
return mobileParameter;
}
public void setMobileParameter(String mobileParameter) {
this.mobileParameter = mobileParameter;
}
public boolean isPostOnly() {
return postOnly;
}
}
生产token 位置
/**
* @author lengleng
* @date 2018/1/8
* 手机号登录成功,返回oauth token
*/
@Component
public class MobileLoginSuccessHandler implements org.springframework.security.web.authentication.AuthenticationSuccessHandler {
private Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ClientDetailsService clientDetailsService;
@Autowired
private AuthorizationServerTokenServices authorizationServerTokenServices;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Basic ")) {
throw new UnapprovedClientAuthenticationException("请求头中client信息为空");
}
try {
String[] tokens = extractAndDecodeHeader(header);
assert tokens.length == 2;
String clientId = tokens[0];
String clientSecret = tokens[1];
JSONObject params = new JSONObject();
params.put("clientId", clientId);
params.put("clientSecret", clientSecret);
params.put("authentication", authentication);
ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
TokenRequest tokenRequest = new TokenRequest(MapUtil.newHashMap(), clientId, clientDetails.getScope(), "mobile");
OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
OAuth2AccessToken oAuth2AccessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
logger.info("获取token 成功:{}", oAuth2AccessToken.getValue());
response.setCharacterEncoding(CommonConstant.UTF8);
response.setContentType(CommonConstant.CONTENT_TYPE);
PrintWriter printWriter = response.getWriter();
printWriter.append(objectMapper.writeValueAsString(oAuth2AccessToken));
} catch (IOException e) {
throw new BadCredentialsException(
"Failed to decode basic authentication token");
}
}
/**
* Decodes the header into a username and password.
*
* @throws BadCredentialsException if the Basic header is not present or is not valid
* Base64
*/
private String[] extractAndDecodeHeader(String header)
throws IOException {
byte[] base64Token = header.substring(6).getBytes("UTF-8");
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
} catch (IllegalArgumentException e) {
throw new BadCredentialsException(
"Failed to decode basic authentication token");
}
String token = new String(decoded, CommonConstant.UTF8);
int delim = token.indexOf(":");
if (delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
}
return new String[]{token.substring(0, delim), token.substring(delim + 1)};
}
}
配置以上自定义
//**
* @author lengleng
* @date 2018/1/9
* 手机号登录配置入口
*/
@Component
public class MobileSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
@Autowired
private MobileLoginSuccessHandler mobileLoginSuccessHandler;
@Autowired
private UserService userService;
@Override
public void configure(HttpSecurity http) throws Exception {
MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
mobileAuthenticationFilter.setAuthenticationSuccessHandler(mobileLoginSuccessHandler);
MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
mobileAuthenticationProvider.setUserService(userService);
http.authenticationProvider(mobileAuthenticationProvider)
.addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
在spring security 配置 上边定一个的那个聚合配置
/**
* @author lengleng
* @date 2018年01月09日14:01:25
* 认证服务器开放接口配置
*/
@Configuration
@EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Autowired
private FilterUrlsPropertiesConifg filterUrlsPropertiesConifg;
@Autowired
private MobileSecurityConfigurer mobileSecurityConfigurer;
@Override
public void configure(HttpSecurity http) throws Exception {
registry
.antMatchers("/mobile/token").permissionAll()
.anyRequest().authenticated()
.and()
.csrf().disable();
http.apply(mobileSecurityConfigurer);
}
}
使用
curl -H "Authorization:Basic cGlnOnBpZw==" -d "grant_type=mobile&scope=server&mobile=17034642119&code=" http://localhost:9999/auth/mobile/token
源码
- 请参考 https://gitee.com/log4j/
- 基于Spring Cloud、Spring Security Oauth2.0开发企业级认证与授权,提供常见服务监控、链路追踪、日志分析、缓存管理、任务调度等实现
- 整个逻辑是参考spring security 自身的 usernamepassword 登录模式实现,可以参考其源码。
- 验证码的发放、校验逻辑比较简单,方法后通过全局fiter 判断请求中code 是否和 手机号匹配集合,重点逻辑是令牌的参数
- Linux用户与“最小权限”原则
- WPF一步一脚印系列(1):万事起头难
- 自定义迭代器使用foreach
- 理解cookie的path和domain属性
- 静态页面设置缓存、动态页面设缓存(不断更新中。。。。)
- 区块链技术如何把你的游戏资产真正变为你的资产
- Python标准库07 信号 (signal包,部分os包)
- 当css属性width设为100%时
- GridView实战一:自定义分页、排序、修改、插入、删除
- Windows下程序打包发布时的小技巧
- Linux的“壳”
- 网页优化系列一:合并文件请求(asp.net版)
- Windows下Thumbnail的开发总结
- 剑指OFFER之调整数组顺序使奇数位于偶数前面找(九度OJ1516)
- java教程
- Java快速入门
- Java 开发环境配置
- Java基本语法
- Java 对象和类
- Java 基本数据类型
- Java 变量类型
- Java 修饰符
- Java 运算符
- Java 循环结构
- Java 分支结构
- Java Number类
- Java Character类
- Java String类
- Java StringBuffer和StringBuilder类
- Java 数组
- Java 日期时间
- Java 正则表达式
- Java 方法
- Java 流(Stream)、文件(File)和IO
- Java 异常处理
- Java 继承
- Java 重写(Override)与重载(Overload)
- Java 多态
- Java 抽象类
- Java 封装
- Java 接口
- Java 包(package)
- Java 数据结构
- Java 集合框架
- Java 泛型
- Java 序列化
- Java 网络编程
- Java 发送邮件
- Java 多线程编程
- Java Applet基础
- Java 文档注释
- 淘宝用户行为数据分析
- PyTorch中Transformer模型的搭建
- A轮公司数据分析面试经验
- Pytorch转NCNN的流程记录
- 算法图解:如何找出栈中的最小值?
- 滴滴出行二面笔试题
- spring JdbcTemplate 查询,参数中使用BeanPropertyRowMapper的作用
- 百万级类别的分类模型的拆分训练
- 关于Spring定义的preDestroy修饰的方法不执行,有以下两种原因,总有一款适合你
- CSP201912-2-回收站选址题目解析-Java ,
- Spring boot框架快速入门
- SpringBoot 跨域问题:Access to XMLHttpRequest at ‘***‘ from origin ‘***‘ has been blocked by CORS policy
- 火车购票-CSP201609-2-Java
- 从后端开发人员的视角:最浅显的理解 Vue
- Sublime怎么默认显示文件路径