Spring Boot 2结合Spring security + JWT实现微信小程序登录

 更新时间:2021年01月25日 10:24:20   作者:tanwubo  
这篇文章主要介绍了Spring Boot 2结合Spring security + JWT实现微信小程序登录,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

项目源码:https://gitee.com/tanwubo/jwt-spring-security-demo

登录

通过自定义的WxAppletAuthenticationFilter替换默认的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登录方式。

用户认证

需要结合JWT来实现用户认证,第一步登录成功后如何颁发token。

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

  @Autowired
  private JwtTokenUtils jwtTokenUtils;

  @Override
  public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
    // 使用jwt管理,所以封装用户信息生成jwt响应给前端
    String token = jwtTokenUtils.generateToken(((WxAppletAuthenticationToken)authentication).getOpenid());
    Map<String, Object> result = Maps.newHashMap();
    result.put(ConstantEnum.AUTHORIZATION.getValue(), token);
    httpServletResponse.setContentType(ContentType.JSON.toString());
    httpServletResponse.getWriter().write(JSON.toJSONString(result));
  }
}

第二步,弃用spring security默认的session机制,通过token来管理用户的登录状态。这里有俩段关键代码。

@Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .sessionManagement()
        // 不创建Session, 使用jwt来管理用户的登录状态
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        ......;
  }

第二步,添加token的认证过滤器。

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

  @Autowired
  private AuthService authService;

  @Autowired
  private JwtTokenUtils jwtTokenUtils;

  @Override
  protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    log.debug("processing authentication for [{}]", request.getRequestURI());
    String token = request.getHeader(ConstantEnum.AUTHORIZATION.getValue());
    String openid = null;
    if (token != null) {
      try {
        openid = jwtTokenUtils.getUsernameFromToken(token);
      } catch (IllegalArgumentException e) {
        log.error("an error occurred during getting username from token", e);
        throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("an error occurred during getting username from token , token is [%s]", token));
      } catch (ExpiredJwtException e) {
        log.warn("the token is expired and not valid anymore", e);
        throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("the token is expired and not valid anymore, token is [%s]", token));
      }catch (SignatureException e) {
        log.warn("JWT signature does not match locally computed signature", e);
        throw new BasicException(ExceptionEnum.JWT_EXCEPTION.customMessage("JWT signature does not match locally computed signature, token is [%s]", token));
      }
    }else {
      log.warn("couldn't find token string");
    }
    if (openid != null && SecurityContextHolder.getContext().getAuthentication() == null) {
      log.debug("security context was null, so authorizing user");
      Account account = authService.findAccount(openid);
      List<Permission> permissions = authService.acquirePermission(account.getAccountId());
      List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new SimpleGrantedAuthority(permission.getPermission())).collect(Collectors.toList());
      log.info("authorized user [{}], setting security context", openid);
      SecurityContextHolder.getContext().setAuthentication(new WxAppletAuthenticationToken(openid, authorities));
    }
    filterChain.doFilter(request, response);
  }
}

接口鉴权

第一步,开启注解@EnableGlobalMethodSecurity

@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class JwtSpringSecurityDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(JwtSpringSecurityDemoApplication.class, args);
  }

}

第二部,在需要鉴权的接口上添加@PreAuthorize注解。

@RestController
@RequestMapping("/test")
public class TestController {

  @GetMapping
  @PreAuthorize("hasAuthority('user:test')")
  public String test(){
    return "test success";
  }

  @GetMapping("/authority")
  @PreAuthorize("hasAuthority('admin:test')")
  public String authority(){
    return "test authority success";
  }

}

到此这篇关于Spring Boot 2结合Spring security + JWT实现微信小程序登录的文章就介绍到这了,更多相关Spring Boot Spring security JWT微信小程序登录内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java实现遍历Map的方法

    java实现遍历Map的方法

    这篇文章主要介绍了java实现遍历Map的方法,以简单实例形式分析了java针对HashMap的遍历技巧,具有一定参考借鉴价值,需要的朋友可以参考下
    2015-09-09
  • 全网最全Mybatis-Plus详解

    全网最全Mybatis-Plus详解

    Mybatis-Plus是一个Mybatis(opens new window)的增强工具,在Mybatis的基础上只做增强不做改变,为简化开发,这篇文章主要介绍了全网最全Mybatis-Plus详解,需要的朋友可以参考下
    2024-05-05
  • idea运行vue项目设置自定义浏览器方式

    idea运行vue项目设置自定义浏览器方式

    这篇文章主要介绍了idea运行vue项目设置自定义浏览器方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • SpringMVC文件上传请求问题分析

    SpringMVC文件上传请求问题分析

    这篇文章主要介绍了SpringMVC文件上传请求,我们发的请求默认都是由DispatcherServlet类的doDispatch()来处理,这个方法的逻辑处理的第一步就是处理文件上传的请求,我们一起来看看是怎么处理的吧
    2024-07-07
  • 带你入门Java的泛型

    带你入门Java的泛型

    这篇文章主要给大家介绍了关于Java中泛型使用的简单方法,文中通过示例代码介绍的非常详细,对大家学习或者使用Java具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
    2021-07-07
  • eclipse怎么引入spring boot项目插件的方法

    eclipse怎么引入spring boot项目插件的方法

    这篇文章主要介绍了eclipse怎么引入spring boot项目插件的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-06-06
  • java中split()方法以及常见算法经典案例

    java中split()方法以及常见算法经典案例

    这篇文章主要介绍了java中split()方法以及常见算法的相关资料,split()方法可以根据指定的正则表达式将字符串分割成多个子字符串,并返回一个字符串数组,文中通过代码介绍的非常详细,需要的朋友可以参考下
    2025-04-04
  • Spring 注入集合实现过程示例详解

    Spring 注入集合实现过程示例详解

    这篇文章主要为大家介绍了Spring 注入集合实现过程示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-09-09
  • Java数据结构之Map与Set专篇讲解

    Java数据结构之Map与Set专篇讲解

    这篇文章通过实例面试题目来讲解Java中Map和Set之间的关系,具有很好的参考价值,Map与Set在面试中经常会遇到。一起跟随小编过来看看吧
    2022-01-01
  • 使用Java实现接口拦截器来监控接口的执行情况

    使用Java实现接口拦截器来监控接口的执行情况

    在排查问题的时候,由于没有对接口的执行情况,以及入参进行监控,所以排查起问题就特别费劲,今天我们就一起来写一个接口的拦截器来监控接口的执行情况吧
    2024-01-01

最新评论