【问题标题】:Getting null token in Jwt token filter when a request is sent in?发送请求时在 Jwt 令牌过滤器中获取空令牌?
【发布时间】:2020-05-28 18:59:28
【问题描述】:

刚开始在保护我的微服务时使用 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);
    }
}
}

如果您需要更多显示的课程,请询问,感谢您的帮助。

【问题讨论】:

  • @dur Request Header: Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGgiOlt7ImF1dGhvcml0eSI6IlJPTEVfQURNSU4ifV0sImlhdCI6MTU2NDYxMjQ4NywiZXhwIjoxNTY0NjE2MDg3fQ.o_m3CXwM0aH0uTy_7fUpff1-xskaWI3-KL6Zdr3BEn4 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0 .3578.98 Safari/537.36 Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9

标签: spring spring-security jwt


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2017-10-21
    • 2019-04-05
    • 2017-10-19
    • 2018-06-09
    • 1970-01-01
    • 2017-04-17
    • 2016-09-05
    • 2019-10-19
    • 2019-01-19
    相关资源
    最近更新 更多