SpringBoot2结合Springsecurity+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 = ateToken(((WxAppletAuthenticationToken)authentication).getOpenid());
Map<String, Object> result = wHashMap();
result.put(Value(), token);
httpServletResponse.setContentType(String());
}
}
第⼆步,弃⽤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 [{}]", RequestURI());
String token = Header(Value());
String openid = null;
if (token != null) {
try {
openid = UsernameFromToken(token);
} catch (IllegalArgumentException e) {
<("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 && Context().getAuthentication() == null) {
log.debug("security context was null, so authorizing user");
springboot原理和机制Account account = authService.findAccount(openid);
List<Permission> permissions = authService.AccountId());
List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> new Permission())).List());
log.info("authorized user [{}], setting security context", openid);
}
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⼩程序登录内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。