您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)怎么在Spring Boot 2中利用Spring security 與JWT登錄微信小程序,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
登錄
通過自定義的WxAppletAuthenticationFilter
替換默認(rèn)的UsernamePasswordAuthenticationFilter
,在UsernamePasswordAuthenticationFilter
中可任意定制自己的登錄方式。
需要結(jié)合JWT來實(shí)現(xiàn)用戶認(rèn)證,第一步登錄成功后如何頒發(fā)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響應(yīng)給前端 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默認(rèn)的session機(jī)制,通過token來管理用戶的登錄狀態(tài)。這里有倆段關(guān)鍵代碼。
@Override protected void configure(HttpSecurity http) throws Exception { http.csrf() .disable() .sessionManagement() // 不創(chuàng)建Session, 使用jwt來管理用戶的登錄狀態(tài) .sessionCreationPolicy(SessionCreationPolicy.STATELESS) ......; }
第二步,添加token的認(rèn)證過濾器。
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); } }
第二部,在需要鑒權(quán)的接口上添加@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登錄微信小程序,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。