为什么访问令牌在邮递员中不起作用,并给出 401 错误

问题描述 投票:0回答:0

我正在学习如何创建和使用 JWT 令牌。我能够创建它但是当我将它指定为身份验证方法并给出 401 错误时它不起作用。

enter image description here

我在 https://jwt.io/ 上检查了我的代币,所有细节都是正确的

这是我的配置文件:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final JwtTokenProvider jwtTokenProvider;
    private final ApplicationContext applicationContext;

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

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .csrf().disable()
                .cors()
                .and()
                .httpBasic().disable()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setStatus(HttpStatus.UNAUTHORIZED.value());
                    response.getWriter().write("Unauthorized.");
                })
                .accessDeniedHandler((request, response, accessDeniedException) -> {
                    response.setStatus(HttpStatus.FORBIDDEN.value());
                    response.getWriter().write("FORBIDDEN.");
                })
                .and()
                .authorizeHttpRequests()
                .requestMatchers("/get-password/**").permitAll()
                .requestMatchers("/login/**").permitAll()
                .requestMatchers("/main/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
                .addFilterBefore(new JwtTokenFilter(jwtTokenProvider), UsernamePasswordAuthenticationFilter.class);

        return httpSecurity.build();
    }
}

这是我的控制器:

@Log4j2
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class AuthorizationController {
    private final AuthService authService;
    private final UsersRepository usersRepository;

    @PostMapping("/login")
    public JwtResponse login(@RequestBody JwtRequest loginRequest){
        return authService.login(loginRequest);
    }

    @PostMapping("/refresh")
    public JwtResponse refresh(@RequestBody String refreshToken) {
        return authService.refresh(refreshToken);
    }
}

spring-boot spring-security jwt http-status-code-401
© www.soinside.com 2019 - 2024. All rights reserved.