You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring认证异常:登录成功后仍重定向至登录页求助

Hey there, let's break down the issues causing your login redirect loop and fix them step by step:

1. Your Custom Login Controller Is Breaking Spring Security's Default Flow

The @RequestMapping("/login") method in your LoginController is overriding Spring Security's built-in authentication logic. Here's why it's problematic:

  • You're not validating the user's password at all—you only check if the username exists in the database
  • Manually creating the Authentication object this way doesn't integrate properly with Spring Security's session management
  • You're incorrectly adding a loginError attribute even when you print "success login", which confuses the flow

Fix: Delete this entire /login handler method. Spring Security will automatically handle POST requests to /login for form-based authentication—you don't need to write this logic yourself.

2. Public Paths Configuration Is Invalid

Your POBLIC_MATCHERS array includes "/**", which matches every possible request. This makes the anyRequest().authenticated() rule completely useless—all requests are allowed without authentication, which explains why your login doesn't seem to take effect.

Fix: Remove "/**" from the public matchers and keep only the paths you truly want to expose:

private static final String[] POBLIC_MATCHERS = {
    "/css/**", "/js/**", "/images/**", 
    "/newUser", "/loginForm", "/resetPassword", "/Register-form", 
    "/forgetPassword", "/products", "/searchByCategory", "/searchProduct", "/productDetail/**"
};

3. Ensure Your User Class Implements UserDetails

Spring Security requires your user entity to implement the UserDetails interface to properly recognize user permissions, enabled status, and other authentication-related properties. If your User class doesn't implement this, add the required methods:

@Entity
public class User implements UserDetails {
    // Your existing fields (id, username, password, enabled, etc.)

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // Return user roles/permissions—example below uses a default role
        return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER"));
    }

    @Override
    public boolean isAccountNonExpired() {
        return true; // Adjust based on your business logic
    }

    @Override
    public boolean isAccountNonLocked() {
        return true; // Adjust based on your business logic
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true; // Adjust based on your business logic
    }

    @Override
    public boolean isEnabled() {
        return this.enabled; // Map to your entity's enabled field
    }

    // Ensure these return your entity's actual username/password fields
    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public String getPassword() {
        return this.password;
    }
}

4. Tweak Spring Security Configuration for Proper Redirects

Update your configure(HttpSecurity http) method to explicitly define the login processing URL and success redirect:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers(POBLIC_MATCHERS).permitAll()
            .anyRequest().authenticated()
            .and()
        .csrf().disable()
        .cors().disable()
        .formLogin()
            .loginPage("/loginForm") // Your login page path
            .loginProcessingUrl("/login") // Spring Security handles POST requests to this URL
            .defaultSuccessUrl("/myAccount") // Redirect here after successful login
            .failureUrl("/loginForm?error=true")
            .permitAll()
            .and()
        .logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
            .logoutSuccessUrl("/loginForm?logout")
            .deleteCookies("remember-me")
            .permitAll()
            .and()
        .rememberMe();
}

5. Verify Your Login Form's Submission Path

Make sure your loginForm HTML points to the correct login processing URL with the right parameter names:

<form action="/login" method="post">
    <input type="text" name="username" placeholder="Username"/>
    <input type="password" name="password" placeholder="Password"/>
    <button type="submit">Login</button>
</form>

(Use usernameParameter and passwordParameter in your formLogin() config if you need to customize these field names.)

After fixing these issues, Spring Security's default authentication flow will work as expected: it will validate the username/password against your UserSecurityService, set the authenticated user in the security context, and redirect to /myAccount on success.

内容的提问来源于stack exchange,提问作者S.Amine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:45:00