|
|
package com.tianbo.warehouse.security.filter;
|
|
|
|
|
|
import com.alibaba.fastjson.JSON;
|
|
|
import com.alibaba.fastjson.JSONObject;
|
|
|
import com.tianbo.warehouse.model.USERS;
|
|
|
import com.tianbo.warehouse.security.CustomUserDetailService;
|
|
|
import com.tianbo.warehouse.util.RedisUtils;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
|
import org.springframework.security.core.userdetails.User;
|
|
|
import org.springframework.security.core.userdetails.UserDetails;
|
|
|
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
|
|
|
import org.springframework.stereotype.Component;
|
...
|
...
|
@@ -23,10 +29,14 @@ import java.io.IOException; |
|
|
* 注意此过滤器每次都会被访问,每个URL带TOKEN 访问这里然后去查用户的资料 会造成数据库压力。
|
|
|
* !!!!后期要把用户资料存储在Redis中,然后用户资料从redis中取,减少数据库压力。
|
|
|
*/
|
|
|
@Slf4j
|
|
|
@Component
|
|
|
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
|
|
|
|
|
|
@Autowired
|
|
|
RedisUtils redisUtils;
|
|
|
|
|
|
@Autowired
|
|
|
CustomUserDetailService userDetailService;
|
|
|
|
|
|
@Override
|
...
|
...
|
@@ -38,10 +48,16 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{ |
|
|
//请求体为 Bearer token
|
|
|
String authHeader = request.getHeader("Authorization");
|
|
|
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
|
|
//获取具体token值,不用了
|
|
|
final String authToken = authHeader.substring("Bearer ".length());
|
|
|
|
|
|
String username = JwtTokenUtil.parseToken(authToken);
|
|
|
|
|
|
// String username = JwtTokenUtil.parseToken(authToken);
|
|
|
String userJson = redisUtils.get(authToken);
|
|
|
try {
|
|
|
if (userJson!=null){
|
|
|
USERS u = JSON.parseObject(userJson,USERS.class);
|
|
|
String username = u.getUsername();
|
|
|
//有JWT 没有登录,去JWT的 信息 获取用户信息,赋予登录
|
|
|
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
|
|
|
UserDetails userDetails = userDetailService.loadUserByUsername(username);
|
...
|
...
|
@@ -53,8 +69,17 @@ public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{ |
|
|
SecurityContextHolder.getContext().setAuthentication(authentication);
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
}catch (Exception e){
|
|
|
e.printStackTrace();
|
|
|
log.error(e.toString());
|
|
|
}
|
|
|
|
|
|
}else{
|
|
|
log.warn("token验证未通过{}",authHeader);
|
|
|
}
|
|
|
|
|
|
filterChain.doFilter(request, response);
|
|
|
}
|
|
|
} |
...
|
...
|
|