温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在Spring Boot 2中利用Spring security 与JWT登录微信小程序

发布时间:2021-01-25 15:36:22 来源:亿速云 阅读:1407 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关怎么在Spring Boot 2中利用Spring security 与JWT登录微信小程序,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

登录

通过自定义的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登录微信小程序,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI