飞道的博客

Spring Security 实战干货:微信小程序登录与Spring Security结合的思路分享

528人阅读  评论(0)


关注并星标,文末获取相关学习资料

1. 前言

原本打算把Spring SecurityOAuth2.0的机制讲完后,用小程序登录来实战一下,发现小程序登录流程和Spring SecurityOAuth 2.0登录的流程有点不一样,就把写了半天的东西全部推翻了。但是,但是过了一天之后,突然感觉又可以了。我们来一起试一试。

2. 小程序登录流程分析

小程序的登录流程是这样的:

微信小程序登录时序图

而在Spring Security中的OAuth 2.0 Code模式是这样的:

Spring Security OAuth2.0 Code模式时序图

从这两张图上看最大的差别就是微信小程序中获取code不需要通过后端服务器的调用,而Spring Security中需要(第1步,第2步,第3步)。腾讯应该也是借鉴了OAuth 2.0,但是做了一些改动。

让我放弃的也是这个差别,有没有人能想到解决方法呢?

假如说小程序已经持有了code,它依然需要将code传递给后端服务器来执行后面的流程。那么我们能不能利用图2中第3个调用redirectUri的步骤呢?换个角度来看问题第三方就是小程序反正它也是将一个code传递给了后端服务器,只要返回登录状态就行了,反正剩下的登录流程都跟小程序无关。我觉得它是可以的。在Spring Security中我们可以使用code通过tokenUri来换取token。那么在微信小程序登录流程中,code最终换取的只是登录态,没有特定的要求。但是后端肯定需要去获取用户的一些信息,比如openId,用户微信信息之类的。总之要根据微信平台提供的API来实现。通过改造tokenUriuserInfoUri可以做到这一点。

3. 思路借鉴

所有的猜想都没有错,而且我也实现了,但是改造成本过高了,写了很多兼容性的代码,如果不深入Spring Security,很难实现这一点,而且也不好理解。

为了简化实现,我决定借鉴Spring SecurityOAuth 2.0的思路。Filter拦截小程序登录URL,然后通过RestTemplate执行向微信服务器请求获取结果,处理后返回登录态。时序图如下:

小程序登录开发时序图

对应的伪代码实现:


   
  1. package cn.felord.spring.security.filter;
  2. import org.springframework.http.ResponseEntity;
  3. import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
  4. import org.springframework.security.web.util.matcher.RequestMatcher;
  5. import org.springframework.util.Assert;
  6. import org.springframework.util.LinkedMultiValueMap;
  7. import org.springframework.util.MultiValueMap;
  8. import org.springframework.web.client.RestTemplate;
  9. import org.springframework.web.filter.OncePerRequestFilter;
  10. import org.springframework.web.util.UriComponentsBuilder;
  11. import javax.servlet.FilterChain;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import java.io.IOException;
  16. import java.net.URI;
  17. /**
  18.  * 小程序登录过滤器
  19.  *
  20.  * @author felord.cn
  21.  * @since 1.0.4.RELEASE
  22.  */
  23. public class WeChatAppLoginFilter extends OncePerRequestFilter {
  24.     private final RequestMatcher requiresAuthenticationRequestMatcher;
  25.     private final RestTemplate restTemplate;
  26.     private String appId;
  27.     private String secret;
  28.     private static final String WX_URL =  "https://api.weixin.qq.com/sns/jscode2session";
  29.     public WeChatAppLoginFilter(String loginProcessingUrl, String appId, String secret) {
  30.         this.appId = appId;
  31.         this.secret = secret;
  32.         Assert.notNull(loginProcessingUrl,  "loginProcessingUrl must not be null");
  33.         this.requiresAuthenticationRequestMatcher =  new AntPathRequestMatcher(loginProcessingUrl,  "POST");
  34.         this.restTemplate =  new RestTemplate();
  35.     }
  36.     @Override
  37.     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
  38.          // 拦截微信登录
  39.          if (requiresAuthenticationRequestMatcher.matches(request)) {
  40.              //todo 从request中获取 code 参数 这里逻辑根据你的情况自行实现
  41.             String jsCode =  "你自行实现从request中获取";
  42.              //todo 必要的校验自己写
  43.             MultiValueMap<String, String> queryParams =  new LinkedMultiValueMap<>();
  44.             queryParams.add( "appid", this.appId);
  45.             queryParams.add( "secret", this.secret);
  46.             queryParams.add( "js_code", jsCode);
  47.             queryParams.add( "grant_type""authorization_code");
  48.             URI uri = UriComponentsBuilder.fromHttpUrl(WX_URL)
  49.                     .queryParams(queryParams)
  50.                     .build()
  51.                     .toUri();
  52.              //todo 这里 Object 自行封装为具体对象
  53.             ResponseEntity<Object> result = this.restTemplate.getForEntity(uri, Object.class);
  54.              //todo 处理 result 比如后端存储、后端授权、角色资源处理、注册、对session_key的处理等等你需要的业务逻辑
  55.              // 最后放入HttpServletResponse中返回前端返回
  56.         }  else {
  57.             filterChain.doFilter(request, response);
  58.         }
  59.     }
  60. }

最后一定别忘了把过滤器配置到WebSecurityConfigurerAdapterHttpSecurity中去。

4. 总结

本篇讲解了Spring Security和微信小程序登录相结合的思路历程。本来不需要长篇大论OAuth 2.0,之所以写出来是让你明白开发中要善于发现一些相似的东西,通过差异对比来探讨他们结合的可能性,这也是一种自我提升的方法。方法远比结果重要,形成自己的方法论就能富有创造力。关注公众号:码农小胖哥 并设置为星标,回复 2021开工福利 即可获取共计24万字的原创Spring Security入门实战干货资料


转载:https://blog.csdn.net/qq_35067322/article/details/114381460
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场