我正在使用 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/