为什么Spring Security阻止了我的请求?

b5buobof  于 2023-08-02  发布在  Spring
关注(0)|答案(1)|浏览(139)

我是新来的Spring。我正在开发我的网上书店项目。我实现了注销功能,我的请求变成了403。当我检查我以前的版本(没有注销功能)时,一切正常。
下面是一个安全配置:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class BookStoreSecurityConfig {
    @Autowired
    private ProjectAuthenticationProvider authenticationProvider;

    private final JWTTokenGeneratorFilter jwtTokenGeneratorFilter;

    private final LogoutHandler logoutHandler;
    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception{

        http.csrf((csrf)->csrf.disable())
                .authorizeHttpRequests(requests -> requests.requestMatchers("/api/v1/auth/**")
                        .permitAll()
                        .anyRequest()
                        .authenticated()
                ).sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtTokenGeneratorFilter, UsernamePasswordAuthenticationFilter.class)
                .logout(l->l.logoutUrl("/api/v1/auth/logout")
                        .addLogoutHandler(logoutHandler).logoutSuccessHandler((request, response, authentication) ->
                        SecurityContextHolder.clearContext()));
    return http.build();
    }
    @Bean
    public AuthenticationManager authManager(HttpSecurity http) throws Exception{
        AuthenticationManagerBuilder authenticationManagerBuilder
                = http.getSharedObject(AuthenticationManagerBuilder.class);
        authenticationManagerBuilder.authenticationProvider(authenticationProvider);
        return authenticationManagerBuilder.build();
    }

}

字符串
这里是Log Out服务:

@Service
@RequiredArgsConstructor
public class LogoutService implements LogoutHandler {
    private final JWTService jwtService;
    @Override
    public void logout(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        if(authHeader == null || !authHeader.startsWith("Bearer ")){
            return;
        }
        jwt = authHeader.substring(7);
        var storedToken = jwtService.getByToken(jwt).orElse(null);
        if (storedToken != null){
            storedToken.setExpired(true);
            storedToken.setRevoked(true);
            jwtService.save(storedToken);
        }
    }
}


我对认证服务做了一些修改,也许会有帮助:

@Service
@RequiredArgsConstructor
@Log4j2
public class AuthenticationServiceImpl implements AuthenticationService{
    @Autowired
    private AuthenticationManager authenticationManager;
    private final UsersRepository usersRepository;
    private final BCryptPasswordEncoder passwordEncoder;
    private final UserService userService;
    private final UserResetPasswordService userResetPasswordService;
    private final JWTService jwtService;
    public Users save(Users user){
        return usersRepository.save(user);
    }
    @Override
    public AuthenticationDtoResponse authenticate(AuthenticationDtoRequest request) {
        Authentication authObject;
        try {
            authObject = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken
                    (request.getEmail(),request.getPassword()));
            SecurityContextHolder.getContext().setAuthentication(authObject);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new BadCredentialsException("Credentials Invalid");
        }
        Users user = userService.getByUserEmail(request.getEmail()).orElseThrow();
        String jwtToken = jwtService.generateToken(user);
        jwtService.revokeAllUserTokens(user);
        var token = Token.builder()
                .user(user)
                .token(jwtToken)
                .tokenType(TokenType.BEARER)
                .expired(false)
                .revoked(false)
                .build();
        jwtService.save(token);
        return AuthenticationDtoResponse
                .builder()
                .jwt(jwtToken)
                .build();
    }
    @Override
    public UserRegistrationDtoResponse registration(UserRegistrationDtoRequest request) {
        var user = Users.builder()
                .email(request.getEmail())
                .password(passwordEncoder.encode(request.getPassword()))
                .address(request.getAddress())
                .createdAt(LocalDateTime.now())
                .name(request.getName())
                .build();
        this.save(user);
        var jwtToken = jwtService.generateToken(user);
        var token = Token.builder()
                .user(user)
                .token(jwtToken)
                .tokenType(TokenType.BEARER)
                .revoked(false)
                .expired(false)
                .build();
        jwtService.save(token);
        return UserRegistrationDtoResponse.builder()
                .email(user.getEmail())
                .address(user.getAddress())
                .jwt(jwtToken)
                .build();
    }
    @Override
    public void changePassword(UserChangePasswordDtoRequest request, String token) {
        ResetPassword resetPassword = userResetPasswordService.getByToken(token);
        Users user = resetPassword.getUser();
        if(user != null){
            user.setPassword(passwordEncoder.encode(request.getNewPassword()));
            userService.save(user);
        }else{
            throw new RuntimeException("User not found");
        }
    }

}

hfyxw5xn

hfyxw5xn1#

发现一个错误。忘了放!在我的身份验证过滤器中开发注销时。谢谢;

相关问题