Spring Boot 2結(jié)合Spring security + JWT實現(xiàn)微信小程序登錄
項目源碼:https://gitee.com/tanwubo/jwt-spring-security-demo
登錄
通過自定義的WxAppletAuthenticationFilter替換默認的UsernamePasswordAuthenticationFilter,在UsernamePasswordAuthenticationFilter中可任意定制自己的登錄方式。
用戶認證
需要結(jié)合JWT來實現(xià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默認的session機制,通過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的認證過濾器。
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);
}
}
接口鑒權(quán)
第一步,開啟注解@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";
}
}
到此這篇關(guān)于Spring Boot 2結(jié)合Spring security + JWT實現(xiàn)微信小程序登錄的文章就介紹到這了,更多相關(guān)Spring Boot Spring security JWT微信小程序登錄內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java中split()方法以及常見算法經(jīng)典案例
這篇文章主要介紹了java中split()方法以及常見算法的相關(guān)資料,split()方法可以根據(jù)指定的正則表達式將字符串分割成多個子字符串,并返回一個字符串?dāng)?shù)組,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2025-04-04
Java數(shù)據(jù)結(jié)構(gòu)之Map與Set專篇講解
這篇文章通過實例面試題目來講解Java中Map和Set之間的關(guān)系,具有很好的參考價值,Map與Set在面試中經(jīng)常會遇到。一起跟隨小編過來看看吧2022-01-01
使用Java實現(xiàn)接口攔截器來監(jiān)控接口的執(zhí)行情況
在排查問題的時候,由于沒有對接口的執(zhí)行情況,以及入?yún)⑦M行監(jiān)控,所以排查起問題就特別費勁,今天我們就一起來寫一個接口的攔截器來監(jiān)控接口的執(zhí)行情況吧2024-01-01

