Spring Security 5身份验证始终返回302

Spring Security 5身份验证始终返回302,spring,spring-mvc,spring-security,Spring,Spring Mvc,Spring Security,我正在使用SpringSecurity5保护我的web应用程序。我访问/login.jsp并填写用户名和密码,然后单击“登录”提交表单,然后被重定向到/login.jsp。我看到fiddler中http流量的响应状态代码是302 SecurityConfig类: @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { private Data

我正在使用SpringSecurity5保护我的web应用程序。我访问/login.jsp并填写用户名和密码,然后单击“登录”提交表单,然后被重定向到/login.jsp。我看到fiddler中http流量的响应状态代码是302

SecurityConfig类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private DataSource dataSource;

    @Autowired
    protected SecurityConfig(DataSource dataSource
    ) {
        this.dataSource = dataSource;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login.jsp")
                .loginProcessingUrl("/login")
                .permitAll();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select name userName, password, enabled from user where name=?")
                .authoritiesByUsernameQuery("select name userName 'ROLE_USER' from user where name=?")
        ;
    }
}
login.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c"
           uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:url value="/login" var="loginUrl"/>
<form action="${loginUrl}" method="post"> 1
    <c:if test="${param.error != null}"> 2
        <p>
            Invalid username and password.
        </p>
    </c:if>
    <c:if test="${param.logout != null}"> 3
        <p>
            You have been logged out.
        </p>
    </c:if>
    <p>
        <label for="username">Username</label>
        <input type="text" id="username" name="username"/> 4
    </p>
    <p>
        <label for="password">Password</label>
        <input type="password" id="password" name="password"/> 5
    </p>
    <button type="submit" class="btn">Log in</button>
</form>
</body>
</html>

标题
1.
2.

无效的用户名和密码。

3. 您已注销。

用户名 4.

密码 5.

登录
使用successHandler将referer设置为true。这对我来说很有用。否则我也会得到302分

在securityConfig中,需要添加以下代码

@Override
protected void configure(HttpSecurity http) throws Exception {
http
  .authorizeRequests()
  .antMatchers("/login*")
  .permitAll()
  .anyRequest()
  .authenticated()
  .and()
  .formLogin()
  .successHandler(new RefererRedirectionAuthenticationSuccessHandler ());
}


import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

public class RefererRedirectionAuthenticationSuccessHandler extends 
SimpleUrlAuthenticationSuccessHandler
    implements AuthenticationSuccessHandler {

public RefererRedirectionAuthenticationSuccessHandler() {
    super();
    setUseReferer(true);
}

}

}
检查以下链接:

我遇到了这个问题,直到我通过在
configure(HttpSecurity)
方法中包含
.csrf().disable()
关闭了csrf检查。 如果您没有关闭它,那么提供csrf令牌作为隐藏表单字段


。。。虽然我看到您禁用了它

,但这是因为spring默认身份验证成功处理程序查找要重定向的url。 我们可以做的是使用自定义AuthenticationSuccessHandler

我已经使用了下面,没有重定向正在发生

public class AppAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
    protected void handle(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
    }

}
然后定义bean并在configure方法中提供它以确保安全性

@Bean
public AuthenticationSuccessHandler appAuthenticationSuccessHandler(){
     return new AppAuthenticationSuccessHandler();
}
配置方法

http
  .authorizeRequests()
  .antMatchers("/login*")
  .permitAll()
  .anyRequest()
  .authenticated()
  .and()
  .formLogin()
  .successHandler(new appAuthenticationSuccessHandler());

我不知道这个问题是否总是积极的,但如果这可以帮助某人

对我有用的是替换

.formLogin()

在我的Web安全配置适配器类中

因此,我的安全配置如下所示:

protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/login", "/actuator/**", "/clients/refresh", "/oauth/token/revokeById/**", "/tokens/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .httpBasic();
}
  • “登录页面url”与“表单操作”相同
  • 给我看代码
java配置:

http.formLogin().loginPage("/login.html")
html


您只需要为“/login.html”编写控制器,通过http GET方法,将其余部分留给“spring”

文件:

UsernamePasswordAuthenticationFilter
通过
httppost方法匹配
/login.html

我的英语不好,希望我能帮助您

您需要删除successHander()呼叫中的“new”。
http.formLogin().loginPage("/login.html")
<form action="/login.html" method="post">