当前位置: 首页 > 知识库问答 >
问题:

凭据无效后,spring boot安全无法登录

岳浩
2023-03-14

验证用户凭据时遇到问题。当我第一次给出正确的凭据时,一切正常,但首先给出无效的凭据,然后再给出正确的凭据,我会得到无效的凭据错误。我使用邮递员基本身份验证。

我的配置类:


    @Configuration
    @EnableWebSecurity
    public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

        @Autowired
        private UserService userService;

        @Autowired
        private CustomAuthenticationEntryPoint authenticationEntryPoint;

        @Override
        protected void configure(HttpSecurity http) throws Exception {

               http.cors().and().csrf().disable().authorizeRequests()
                    .antMatchers(HttpMethod.POST ,"/login").permitAll()
                    .antMatchers("/admin").hasAuthority("ADMIN")
                    .anyRequest().authenticated().and().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint).and()
                    .sessionManagement()
                    .sessionCreationPolicy(SessionCreationPolicy.ALWAYS).and()
                    .logout()
                    .deleteCookies("remove")
                    .invalidateHttpSession(true);

               http.rememberMe().disable();

        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
                    auth.userDetailsService(this.userService)
                            .and().eraseCredentials(true);
        }

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

和我的控制器类

   



     @PostMapping
            public ResponseEntity loginButtonClicked(HttpServletRequest request) {
                HttpSession session = request.getSession();
                final String authorization = request.getHeader("Authorization");
                String[] authorizationData=null;
                if (authorization != null && authorization.startsWith("Basic")) {
                    // Authorization: Basic base64credentials
                    String base64Credentials = authorization.substring("Basic" .length()).trim();
                    String credentials = new String(Base64.getDecoder().decode(base64Credentials),
                            Charset.forName("UTF-8"));
                    // credentials = username:password
                    authorizationData = credentials.split(":", 2);
                    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(authorizationData[0], authorizationData[1],Arrays.asList(new SimpleGrantedAuthority("USER")));
                    User user = userService.findUserEntityByLogin(authorizationData[0]);
                    if(user != null && user.getFromWhenAcceptLoginAttempts() != null && (user.getFromWhenAcceptLoginAttempts()).isBefore(LocalDateTime.now())){
                        // Authenticate the user
                        Authentication authentication = authenticationManager.authenticate(authRequest);
                        SecurityContext securityContext = SecurityContextHolder.getContext();
                        securityContext.setAuthentication(authentication);

                        // Create a new session and add the security context.
                        session = request.getSession();

                        session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

                        return new ResponseEntity(new LoginResponseObject(200,"ACCESS GRANTED. YOU HAVE BEEN AUTHENTICATED"), HttpStatus.OK);
                    }else{
                        session.getId();
                        SecurityContextHolder.clearContext();
                        if(session != null) {
                            session.invalidate();
                        }
                        return new ResponseEntity(new ErrorObject(403,"TOO MANY LOGIN REQUESTS","YOU HAVE ENTERED TOO MANY WRONG CREDENTIALS. YOUR ACCOUNT HAS BEEN BLOCKED FOR 15 MINUTES.", "/login"), HttpStatus.FORBIDDEN);
                    }
                }else{
                    session.getId();
                    SecurityContextHolder.clearContext();
                    if(session != null) {
                        session.invalidate();
                    }
                    return new ResponseEntity(new ErrorObject(401,"INVALID DATA","YOU HAVE ENTERED WRONG USERNAME/PASSWORD CREDENTIALS", "/login"), HttpStatus.UNAUTHORIZED);
                }

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

            @Bean
            public ObjectMapper objectMapper(){
                return new ObjectMapper();
            }

            @Bean
            public HttpSessionEventPublisher httpSessionEventPublisher() {
                return new HttpSessionEventPublisher();
            } 

共有2个答案

谢阳曜
2023-03-14

尝试在SpringSecurityConfig类中编写.deletecookies(“jsessonid”)

索锐藻
2023-03-14

问题是,由于您的SessionCreationPolicy,请求存储在缓存中。

为了避免此问题,您可以在http安全配置中添加.requestcache().requestcache(new NullRequestCache()),以覆盖默认的请求缓存配置,但要小心,因为这可能会产生另一个副作用(这取决于您的应用程序)。

如果不需要会话,可以选择其他会话策略:

.SessionManagement().SessionCreationPolicy(SessionCreationPolicy.Stateless)

另一种选择是在spring的BasicAuthenticationFilter中进行中继。此筛选器为您执行所有身份验证逻辑。要启用它,您只需在http安全配置中添加.httpbasic()

您可能希望在身份验证成功/失败时添加自定义逻辑。在这种情况下,您只需创建一个自定义筛选器(CustomBasicAuthenticationFilter),该筛选器扩展BasicAuthenticationFilter类并重写OnSuccessfulAuthentication()OnUnSuccessfulAuthentication()方法。您不需要添加.httpbasic(),但需要在正确的位置插入自定义筛选器:

.AddFilterAfter(新建CustomBasicAuthenticationFilter(authenticationManager),LogoutFilter.Class)

这三种解决方案中的任何一种都可以避免您的问题。

 类似资料:
  • 在这里,我已经设置了默认的安全域 以下是我在web.xml中的配置: 以下是AIS.Properties中的配置: UserBean登录功能: 它给了我以下例外:

  • 我想使用脚本化方法(可能是通过)curl,从驱动器api访问一些简单的信息,例如创建日期。从本质上讲,我想在他们的Web界面中编写我可以做的事情:https://developers.google.com/drive/api/v3/reference/files/list。 我一直在使用curl命令,他们在上面的链接的查询中公开该命令: 我为此创建了一个API密钥(目前不受限制)。并使用此应用程序

  • 我正试图将我们的应用程序集成到active Directory中。我遵循了以下入门指南:https://grails.org/wiki/acegisecurity%20plugin%20-%20ldap%20tutorial,但我得到了一个错误: [LDAP:错误代码49-无效凭据];嵌套异常是javax.naming.AuthenticationException:[LDAP:错误代码49-无效

  • 我已经按照你在这篇博客中提到的步骤进行了操作。对于基本dn,他们给出了类似于'base dn-dc=,dc='的内容,但我给出了类似于'ecompany.local'的内容。因为我不是ldap管理员,所以我给了主体作为我的ldap id和我的ldap密码。当我单击test connection时,弹出窗口显示“Liferay已成功连接到LDAP服务器”。 重新启动了服务器。 点击登录。输入ldap

  • 当我简单地运行以下代码时,我总是得到这个错误。 我已将我的证书文件保存在 ,Boto应从中读取我的凭据。 我的设置有错吗? 下面是boto3.set\u stream\u logger('botocore',level='DEBUG')的输出。