简体   繁体   English

API 在所有请求上都需要 JWT 令牌,尽管进行了身份验证配置

[英]API requires JWT Token on all requests despite the authentication configuration

I am attempting to follow this tutorial , which is a follow up to this tutorial , to implement JWT authorization for my API. When I attempt to use the '/authenticate' and '/register', I get the error "JWT Token does not begin with Bearer String".我正在尝试按照本教程(本教程的后续教程)为我的 API 实施 JWT 授权。当我尝试使用“/authenticate”和“/register”时,出现错误“JWT Token does not从 Bearer String 开始”。

Here is the part of the Request filter that throws the error:这是抛出错误的请求过滤器的一部分:

    if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
        jwtToken = requestTokenHeader.substring(7);
        try {
            username = jwtTokenUtil.getUsernameFromToken(jwtToken);
        } catch (IllegalArgumentException e) {
            System.out.println("Unable to get JWT Token");
        } catch (ExpiredJwtException e) {
            System.out.println("JWT Token has expired");
        }
    } else {
        logger.warn("JWT Token does not begin with Bearer String");
    }

Here is the websecurityconfig that should be allowing the 'authenticate' and 'request' requests through.这是应该允许“验证”和“请求”请求通过的 websecurityconfig。 I'm a bit confused as I cannot find where this is actually called in the tutorial:我有点困惑,因为我找不到教程中实际调用它的位置:

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;

    @Autowired
    private UserDetailsService jwtUserDetailsService;

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // configure AuthenticationManager so that it knows from where to load
        // user for matching credentials
        // Use BCryptPasswordEncoder
        auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder());
    }

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

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate", "/register").permitAll().
                // all other requests need to be authenticated
                anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }
}

Attached is a link to the github.附件是 github 的链接。

https://github.com/Dikianify/ReporterAPI.git https://github.com/Dikianify/ReporterAPI.git

Thanks谢谢

Because the jwtRequestFilter is a filter it will be called on every request (including /authenticate & /register), not just those that require authentication.因为 jwtRequestFilter 是一个过滤器,它将在每个请求(包括 /authenticate 和 /register)上调用,而不仅仅是那些需要身份验证的请求。

httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

This is not a problem because the code is simply writing a warning to the logs and passing the request on down for further processing.这不是问题,因为代码只是将警告写入日志并将请求向下传递以进行进一步处理。

logger.warn("JWT Token does not begin with Bearer String");

When the user has been authenticated the Bearer header with the token should come through in each request for the filter to extract username.当用户通过身份验证后,带有令牌的 Bearer header 应该在过滤器提取用户名的每个请求中通过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我可以拥有两个 Spring 安全配置类:一个使用基本身份验证保护一些 API,另一个使用 JWT 令牌保护 API? - Can I have two Spring Security configuration classes: one that protect some API with basic authentication and another protecting APIs with JWT token? 使用 jwt 进行身份验证如何验证 http 请求 - Authentication using jwt how to validate http requests 如何通过 Spring Security (Spring Boot 2.7.0) 生成的 JWT 令牌对 ASP.NET Core Web API 6 进行身份验证? - How to authentication for ASP.NET Core Web API 6 by JWT token generated by Spring Security (Spring Boot 2.7.0)? Spring Security JWT过滤器适用于所有请求 - Spring Security JWT Filter applies on all requests Spring Security:用于API的JWT令牌和用于Web的会话 - Spring Security: JWT token for API and session for web JWT 令牌作为 API 中用户详细信息的来源? - JWT Token as source of User Details in an API? 使用有效的 JWT 令牌调用 keycloak 认证的 API - Call keycloak authenticated API with valid JWT token Spring Security的身份验证问题,资源API上的JWT - Authentication issue with spring security, JWT on resource API Spring 启动安全性 - 允许使用过期 JWT 令牌的用户请求 - Spring boot security - allowing user requests with expired JWT token 如何从 JWT 令牌身份验证中获取声明值 - how to get claims value from JWT token authentication
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM