Spring Security 5 身份验证总是返回 302

标签 spring spring-mvc spring-security

我正在使用 Spring-Security 5 来保护我的 Web 应用程序。我访问/login.jsp并填写用户名和密码,然后点击“登录”提交表单,然后被重定向到/login.jsp。我看到 fiddler 中那个 http 流量的响应状态代码是 302。
安全配置类:

@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=?")
        ;
    }
}
登录.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>

最佳答案

这是因为 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());

关于Spring Security 5 身份验证总是返回 302,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50157911/

相关文章:

spring - 在哪里放置组件scan

java - Spring的@Required注解推荐用法

java - 无法解析 Maven 项目中的 Spring Security 类

java - 定义 HibernateExceptionTranslator : No persistence exception translators found in bean factory

java - 如何将参数化 JUnit 测试运行器与使用 Spring 注入(inject)的字段一起使用?

java - spring mvc 3 和静态内容

Spring 验证@AssertTrue

java - 无法将 HashMap 类型转换为 HashMap 本身且内部包含 HashMap 对象的对象

java - 了解 Spring 的身份验证对象及其创建的上下文

spring - 处理 UserRedirectRequiredException(需要重定向才能获得用户批准)