最后一步整合jwt,前面1,2如果认真操作了,基本就掌握了大概流程,下面只讲jwt,参考网上博客自己整理的
重新编写配置类继承WebSecurityConfigurerAdapter,或者直接再原来的加上
JWTLoginFilter用于生成token类 ,JWTAuthenticationFilter用于安全验证类
public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter{
private AuthenticationManager authenticationManager;
public JWTLoginFilter(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
// 接收并解析用户凭证
@Override
public Authentication attemptAuthentication(HttpServletRequest req,
HttpServletResponse res) throws AuthenticationException {
try {
User user = new ObjectMapper()
.readValue(req.getInputStream(), User.class);
return authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(
user.getUsername(),
user.getPassword(),
new ArrayList<>())
);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// 用户成功登录后,这个方法会被调用,我们在这个方法里生成token
@Override
protected void successfulAuthentication(HttpServletRequest req,
HttpServletResponse res,
FilterChain chain,
Authentication auth) throws IOException, ServletException {
//token生成方式User对象,一天过期,密钥HS512模式,并添加Bearer作为头部
String token = Jwts.builder()
.setSubject(((User) auth.getPrincipal()).toString())
.setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 24 * 1000))
.signWith(SignatureAlgorithm.HS512, "MyJwtSecret")
.compact();
//用于客户端接收repsonseHeader
res.addHeader("Access-Control-Expose-Headers", "Authorization");
String allowHeaders = "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With, Authorization";
res.addHeader("Access-Control-Allow-Headers", allowHeaders);
res.addHeader("Authorization", "Bearer " + token);
}
public class JWTAuthenticationFilter extends BasicAuthenticationFilter{
public JWTAuthenticationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
String header = request.getHeader("Authorization");
if (header == null || !header.startsWith("Bearer ")) {
chain.doFilter(request, response);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request, response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
String token = request.getHeader("Authorization");
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey("MyJwtSecret")
.parseClaimsJws(token.replace("Bearer ", ""))
.getBody()
.getSubject();
if (user != null) {
//此段是用于提取用户的认证authorities信息,具体操作看项目设计,如果不要sercuity验证可直接使用下段注释部分
// return new UsernamePasswordAuthenticationToken(user, null, new ArrayList<>());
List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>(10);
String use = user.replace("User(","").replace(")","");
String[] uselist =use.split(",");
for(String a :uselist){
if(a.contains("roleName")){
String b = a.replace("roleName=","");
if(!StringUtils.isEmpty(b)){
for(String c: b.split(",")){
if(!StringUtils.isEmpty(c)){
authorities.add(new SimpleGrantedAuthority(c.trim()));
}
}
}
}
}
return new UsernamePasswordAuthenticationToken(user, null, authorities);
}
return null;
}
return null;
}
}
测试验证
将请求Authorization放入请求头
不放