由于用户帐户被锁定而无法进行身份验证,Springboot安全身份验证错误

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

“我对 Java 和 Spring boot 应用程序相对较新,我正在尝试遵循 YouTube 教程。 我已经创建了注册和登录端点,并使用邮递员进行了测试,并且注册有效,并且正在使用加密密码在数据库中创建详细信息。当我尝试使用相同的凭据来测试登录端点时。我收到 403 请求禁止错误。我在 Spring Security 中放置了一个调试器。”

“下面是我的 JWTauthenticationFilter 的代码”:



    ```@Component
    @RequiredArgsConstructor
    public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JWTUtil jwtUtil;
    private final UserService userService;

    @Override
    protected void doFilterInternal(@NonNull HttpServletRequest httpServletRequest,
                                    @NonNull HttpServletResponse httpServletResponse,
                                    @NonNull FilterChain filterChain) throws ServletException,     IOException {
        final String authHeader = httpServletRequest.getHeader("Authorization");
        final String jwt;
        final String userEmail;
        if(StringUtils.isEmpty(authHeader) || !StringUtils.startsWith(authHeader, "Bearer ")) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        jwt = authHeader.substring(7);
        userEmail = jwtUtil.extractUserName(jwt);
        if(StringUtils.isNoneEmpty(userEmail)
        && SecurityContextHolder.getContext().getAuthentication() == null){
            UserDetails userDetails =        userService.userDetailsService().loadUserByUsername(userEmail);
            if(jwtUtil.isTokenValid(jwt, userDetails)){
                SecurityContext context = SecurityContextHolder.createEmptyContext();
                UsernamePasswordAuthenticationToken authToken = new     UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authToken.setDetails(new     WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                context.setAuthentication(authToken);
                SecurityContextHolder.setContext(context);
            }
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }


    }```

下面是我的 WebSecurityConfiguration 的代码:

@EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor public class WebSecurityConfiguration { private final JwtAuthenticationFilter jwtAuthenticationFilter; private final UserService userService; @Bean public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf(AbstractHttpConfigurer::disable).authorizeHttpRequests(request -> request.requestMatchers("/api/auth/**").permitAll() .requestMatchers("/api/admin/**").hasAnyAuthority(UserRole.ADMIN.name()) .requestMatchers("/api/customer/**").hasAnyAuthority(UserRole.CUSTOMER.name()) .anyRequest().authenticated()).sessionManagement(manger -> manger.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authenticationProvider(authenticationProviders()) .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return httpSecurity.build(); } @Bean public PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public AuthenticationProvider authenticationProviders() { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userService.userDetailsService()); authProvider.setPasswordEncoder(passwordEncoder()); return authProvider; } @Bean public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception { return authenticationConfiguration.getAuthenticationManager(); } }``` </code></pre> I tried using webresources and different GPTs and there seems to be no clarity with what is going on... I did exactly as I was shown in the tutorial. And the below is the console : I hope someone figures it out, I have tried extensively looking for a solution... <pre><code> ```2024-03-21T14:58:27.212-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.security.web.FilterChainProxy : Securing POST /api/auth/login </code>` <code>2024-03-21T14:58:27.213-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext</code> <code>2024-03-21T14:58:27.213-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.security.web.FilterChainProxy : Secured POST /api/auth/login</code> <code>2024-03-21T14:58:27.317-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.s.a.dao.DaoAuthenticationProvider : Failed to authenticate since user account is locked</code> <code>2024-03-21T14:58:27.320-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access</code> <code>2024-03-21T14:58:27.325-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.security.web.FilterChainProxy : Securing POST /error</code> <code>2024-03-21T14:58:27.325-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext</code> <code>2024-03-21T14:58:27.327-04:00 DEBUG 14564 --- [nio-9000-exec-3] o.s.s.w.a.Http403ForbiddenEntryPoint : Pre-authenticated entry point called. Rejecting access</code> <code>2024-03-21T15:54:37.576-04:00 INFO 14564 --- [ionShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'``` </code></pre>
java authentication spring-security spring-boot-security
1个回答
0
投票

我能够通过身份验证教程找到上述问题的答案, 当 User 类实现 UserDetails 时, getAuthorities() 方法将被重写。 “ROLE_”字符串需要与用户角色一起传递给该方法。下面是方法...

@Override public Collection<? extends GrantedAuthority> getAuthorities() { return List.of(new SimpleGrantedAuthority("ROLE_" +userRole.name())); }

© www.soinside.com 2019 - 2024. All rights reserved.