【转载】spring-security-oauth2(十九) 重构用户名密码登陆

在开始重构前我们来回忆下前面的流程

三种方式登陆成功后组装后续流程返回token,必须携带basic client信息(因为需要它获取clientDetails信息)

 

 

 ok分析完流程后我们进行重构。先直接用浏览器的配置进行修改后续继续重构优化

登陆成功转换token处理


 
 
  1. package com.rui.tiger.auth.core.authentication;
  2. import com.alibaba.fastjson.JSON;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import com.rui.tiger.auth.core.model.enums.LoginTypeEnum;
  5. import com.rui.tiger.auth.core.properties.SecurityProperties;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.apache.commons.collections.MapUtils;
  8. import org.apache.commons.lang.StringUtils;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.security.authentication.BadCredentialsException;
  11. import org.springframework.security.core.Authentication;
  12. import org.springframework.security.oauth2.common.OAuth2AccessToken;
  13. import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
  14. import org.springframework.security.oauth2.config.annotation.configuration.ClientDetailsServiceConfiguration;
  15. import org.springframework.security.oauth2.provider.*;
  16. import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
  17. import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
  18. import org.springframework.stereotype.Component;
  19. import javax.servlet.ServletException;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. import java.io.IOException;
  23. import java.util.Base64;
  24. /**
  25. * 认证成功处理器
  26. * {@link SavedRequestAwareAuthenticationSuccessHandler}是Spring Security默认的成功处理器
  27. *
  28. * @author CaiRui
  29. * @date 2018-12-6 12:39
  30. */
  31. @Component( "tigerAuthenticationSuccessHandler")
  32. @Slf4j
  33. public class TigerAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
  34. @Autowired
  35. private SecurityProperties securityProperties;
  36. /**
  37. * 授权服务器:自动配置的
  38. * @see ClientDetailsServiceConfiguration#clientDetailsService()
  39. */
  40. @Autowired
  41. private ClientDetailsService clientDetailsService;
  42. @Autowired
  43. private AuthorizationServerTokenServices authorizationServerTokenServices;
  44. @Autowired
  45. private ObjectMapper objectMapper;
  46. @Override
  47. public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
  48. log.info( "登录成功");
  49. /**
  50. * @see BasicAuthenticationFilter#doFilterInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, javax.servlet.FilterChain)
  51. * */
  52. String header = request.getHeader( "Authorization");
  53. if (header == null || !header.startsWith( "Basic ")) {
  54. // 不被认可的客户端异常
  55. throw new UnapprovedClientAuthenticationException( "没有Authorization请求头");
  56. }
  57. // 解析请Authorization 获取client信息 client-id: tigerauth client-secret: 123456
  58. String[] tokens = extractAndDecodeHeader(header, request);
  59. assert tokens.length == 2;
  60. String clientId = tokens[ 0];
  61. String clientSecret = tokens[ 1];
  62. ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
  63. // 判定提交的是否与查询的匹配
  64. if (clientDetails == null) {
  65. throw new UnapprovedClientAuthenticationException( "clientId对应的配置信息不存在:" + clientId);
  66. } else if (!StringUtils.equals(clientDetails.getClientSecret(), clientSecret)) {
  67. throw new UnapprovedClientAuthenticationException( "clientSecret不匹配:" + clientId);
  68. }
  69. /** @see DefaultOAuth2RequestFactory#createTokenRequest(java.util.Map, org.springframework.security.oauth2.provider.ClientDetails)
  70. * requestParameters,不同的授权模式有不同的参数,这里自定义的模式,没有参数
  71. * String clientId,
  72. * Collection<String> scope, 给自己的前段使用,默认用所有的即可
  73. * String grantType 自定义 custom
  74. * */
  75. TokenRequest tokenRequest = new TokenRequest(MapUtils.EMPTY_SORTED_MAP, clientId, clientDetails.getScope(), "custom");
  76. OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
  77. /**
  78. * @see org.springframework.security.oauth2.provider.token.AbstractTokenGranter#getOAuth2Authentication(org.springframework.security.oauth2.provider.ClientDetails, org.springframework.security.oauth2.provider.TokenRequest)
  79. * */
  80. OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);
  81. OAuth2AccessToken accessToken = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
  82. response.setContentType( "application/json;charset=UTF-8");
  83. /* log.info("TOKEN信息:" + JSON.toJSONString(accessToken));
  84. response.getWriter().write(JSON.toJSONString(accessToken));*/
  85. log.info( "jack TOKEN信息:" + objectMapper.writeValueAsString(accessToken));
  86. response.getWriter().write(objectMapper.writeValueAsString(accessToken));
  87. }
  88. /**
  89. * Decodes the header into a username and password.
  90. * @throws BadCredentialsException if the Basic header is not present or is not valid
  91. * Base64
  92. */
  93. private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
  94. byte[] base64Token = header.substring( 6).getBytes( "UTF-8");
  95. byte[] decoded;
  96. try {
  97. decoded = Base64.getDecoder().decode(base64Token);
  98. } catch (IllegalArgumentException e) {
  99. throw new BadCredentialsException(
  100. "Failed to decode basic authentication token");
  101. }
  102. String token = new String(decoded, "UTF-8");
  103. int delim = token.indexOf( ":");
  104. if (delim == - 1) {
  105. throw new BadCredentialsException( "Invalid basic authentication token");
  106. }
  107. return new String[]{token.substring( 0, delim), token.substring(delim + 1)};
  108. }
  109. }

权限配置器


 
 
  1. package com.rui.tiger.auth.app;
  2. import com.rui.tiger.auth.core.config.CaptchaSecurityConfig;
  3. import com.rui.tiger.auth.core.config.SmsAuthenticationSecurityConfig;
  4. import com.rui.tiger.auth.core.properties.SecurityConstants;
  5. import com.rui.tiger.auth.core.properties.SecurityProperties;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.security.config.annotation.web.builders.HttpSecurity;
  9. import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
  10. import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
  11. import org.springframework.security.web.authentication.AuthenticationFailureHandler;
  12. import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
  13. import org.springframework.social.security.SpringSocialConfigurer;
  14. /**
  15. * @author CaiRui
  16. * @date 2019-04-17 08:38
  17. */
  18. @Configuration
  19. @EnableResourceServer
  20. public class TigerResourceServerConfig extends ResourceServerConfigurerAdapter{
  21. @Autowired
  22. private AuthenticationSuccessHandler tigerAuthenticationSuccessHandler;
  23. @Autowired
  24. private AuthenticationFailureHandler tigerAuthenticationFailureHandler;
  25. @Autowired
  26. private SmsAuthenticationSecurityConfig smsAuthenticationSecurityConfig; //短信登陆配置
  27. @Autowired
  28. private SpringSocialConfigurer tigerSpringSocialConfigurer;
  29. @Autowired
  30. private SecurityProperties securityProperties;
  31. @Override
  32. public void configure(HttpSecurity http) throws Exception {
  33. /**
  34. * 表单密码配置
  35. */
  36. http.formLogin()
  37. .loginPage(SecurityConstants.DEFAULT_UNAUTHENTICATION_URL)
  38. .loginProcessingUrl(SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_FORM) //
  39. .defaultSuccessUrl( "/index.html")
  40. .successHandler(tigerAuthenticationSuccessHandler)
  41. .failureHandler(tigerAuthenticationFailureHandler);
  42. http
  43. /*.apply(captchaSecurityConfig) //图形验证码的有问题 先不处理
  44. .and()*/
  45. .apply(smsAuthenticationSecurityConfig)
  46. .and()
  47. .apply(tigerSpringSocialConfigurer)
  48. .and()
  49. .authorizeRequests()
  50. .antMatchers(
  51. SecurityConstants.DEFAULT_UNAUTHENTICATION_URL, //权限认证
  52. SecurityConstants.DEFAULT_LOGIN_PROCESSING_URL_MOBILE, //手机
  53. securityProperties.getBrowser().getLoginPage(), //登录页面
  54. SecurityConstants.DEFAULT_VALIDATE_CODE_URL_PREFIX+ "/*", // /captcha/* 验证码放行
  55. securityProperties.getBrowser().getSignupUrl(),
  56. //这个第三方自定义权限 后续抽离出去 可配置
  57. securityProperties.getBrowser().getLoginOut(),
  58. "/user/regist",
  59. "/index.html",
  60. securityProperties.getBrowser().getSession().getInvalidSessionUrl())
  61. .permitAll()
  62. .anyRequest()
  63. .authenticated()
  64. .and()
  65. .csrf().disable();
  66. }
  67. }

ok 我们来测试下

 带上token访问用户信息

ok 下章我们 重构短信登陆。

文章转载至:https://blog.csdn.net/ahcr1026212/article/details/89412623

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值