|
@@ -5,6 +5,7 @@ import jakarta.servlet.FilterChain;
|
|
|
import jakarta.servlet.ServletException;
|
|
|
import jakarta.servlet.http.HttpServletRequest;
|
|
|
import jakarta.servlet.http.HttpServletResponse;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.security.core.context.SecurityContextHolder;
|
|
|
import org.springframework.security.core.userdetails.User;
|
|
|
import org.springframework.security.oauth2.jwt.Jwt;
|
|
@@ -20,6 +21,7 @@ import java.util.HashSet;
|
|
|
import java.util.List;
|
|
|
import java.util.Set;
|
|
|
|
|
|
+@Slf4j
|
|
|
public class JWTAuthorizationFilter extends OncePerRequestFilter {
|
|
|
|
|
|
private final JwtDecoder jwtDecoder;
|
|
@@ -44,22 +46,26 @@ public class JWTAuthorizationFilter extends OncePerRequestFilter {
|
|
|
filterChain.doFilter(request, response);
|
|
|
return;
|
|
|
}
|
|
|
- Jwt decode = jwtDecoder.decode(token);
|
|
|
- if (decode == null || decode.getExpiresAt() == null || decode.getExpiresAt().compareTo(Instant.now()) <= 0) {
|
|
|
- filterChain.doFilter(request, response);
|
|
|
- return;
|
|
|
- }
|
|
|
- // 将UserDetails存储到SecurityContextHolder中
|
|
|
- Set<CustomGrantedAuthority> authorityList = new HashSet<>();
|
|
|
- List<String> scopeList = decode.getClaimAsStringList("scope");
|
|
|
- for (String scope : scopeList) {
|
|
|
- CustomGrantedAuthority auth = new CustomGrantedAuthority(scope);
|
|
|
- authorityList.add(auth);
|
|
|
+ try {
|
|
|
+ Jwt decode = jwtDecoder.decode(token);
|
|
|
+ if (decode == null || decode.getExpiresAt() == null || decode.getExpiresAt().compareTo(Instant.now()) <= 0) {
|
|
|
+ filterChain.doFilter(request, response);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ // 将UserDetails存储到SecurityContextHolder中
|
|
|
+ Set<CustomGrantedAuthority> authorityList = new HashSet<>();
|
|
|
+ List<String> scopeList = decode.getClaimAsStringList("scope");
|
|
|
+ for (String scope : scopeList) {
|
|
|
+ CustomGrantedAuthority auth = new CustomGrantedAuthority(scope);
|
|
|
+ authorityList.add(auth);
|
|
|
+ }
|
|
|
+ LinkedTreeMap<String, Object> userInfo = decode.getClaim("userInfo");
|
|
|
+ User user = new User(decode.getClaimAsString("sub"), "", true, true, true, true, authorityList);
|
|
|
+ JwtAuthorizationToken authenticationToken = new JwtAuthorizationToken(user, authorityList);
|
|
|
+ SecurityContextHolder.getContext().setAuthentication(authenticationToken);
|
|
|
+ } catch (Exception ex) {
|
|
|
+ log.error(ex.getMessage());
|
|
|
}
|
|
|
- LinkedTreeMap<String, Object> userInfo = decode.getClaim("userInfo");
|
|
|
- User user = new User(decode.getClaimAsString("sub"), "", true, true, true, true, authorityList);
|
|
|
- JwtAuthorizationToken authenticationToken = new JwtAuthorizationToken(user, authorityList);
|
|
|
- SecurityContextHolder.getContext().setAuthentication(authenticationToken);
|
|
|
filterChain.doFilter(request, response);
|
|
|
}
|
|
|
}
|