发送请求时,是否在Jwt令牌过滤器中获取空令牌?

时间:2019-07-31 21:00:07

标签: spring spring-security jwt

在保护微服务时,刚开始使用Jwt令牌,并且在发送请求但不知道从何处发送请求时,在JwtTokenFilter类中不断获取空令牌,并且很难理解为什么?

JwtTokenFilter.class

public class JwtTokenFilter extends OncePerRequestFilter {

private JwtTokenProvider jwtTokenProvider;

public JwtTokenFilter(JwtTokenProvider jwtTokenProvider) {
    this.jwtTokenProvider = jwtTokenProvider;
}

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
    String token = jwtTokenProvider.resolveToken(request);

    System.out.println("Token: " + token);

    try {
        if (token != null && jwtTokenProvider.validateToken(token)) {

            Authentication auth = jwtTokenProvider.getAuthentication(token);
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
    } catch (CustomException ex) {

        SecurityContextHolder.clearContext();
        response.sendError(ex.getHttpStatus().value(), ex.getMessage());
        return;
    }

    filterChain.doFilter(request, response);
}

SecurityConfig.class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtTokenProvider jwtTokenProvider;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors()
            .and()
            .csrf().disable()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/auth/login").permitAll()
            .antMatchers("/auth/register").permitAll()
            .antMatchers("/auth/{username}").permitAll()
            .anyRequest()
            .authenticated();

    http.addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);
}

@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }
}

JwtTokenProvider.class

@Component
public class JwtTokenProvider {

@Value("$security.jwt.token.secret-key")
private String secretKey;

private long validityInMilliseconds = 3600000;

@Autowired
private CustomUserDetails customUserDetails;

@PostConstruct
protected void init() {
    secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
}

public String createToken(String username, List<Role> roles) {
    Claims claims = Jwts.claims().setSubject(username);
    claims.put("auth", roles.stream().map(s -> new SimpleGrantedAuthority(s.getAuthority())).collect(Collectors.toList()));

    Date now = new Date();
    Date validity = new Date(now.getTime() + validityInMilliseconds);

    return Jwts.builder()//
            .setClaims(claims)//
            .setIssuedAt(now)//
            .setExpiration(validity)//
            .signWith(SignatureAlgorithm.HS256, secretKey)//
            .compact();

}

public Authentication getAuthentication(String token) {
    UserDetails userDetails = customUserDetails.loadUserByUsername(getUsername(token));
    return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
}

public String getUsername(String token) {
    return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody().getSubject();
}

public String resolveToken(HttpServletRequest req) {
    String bearerToken = req.getHeader("Authorization");
    if (bearerToken != null &&  bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7);
    }

    return null;
}

public boolean validateToken(String token) {
    try {
        Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);
        return true;
    } catch (JwtException | IllegalArgumentException e) {
        throw new CustomException("Expired or invalid JWT token", HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
}

如果您需要显示其他课程,请询问,谢谢。

1 个答案:

答案 0 :(得分:0)

意识到问题是我如何在春季配置中向网关微服务注册它。全部感谢您的帮助。