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

5gfr0r5j  于 2022-11-11  发布在  Spring
关注(0)|答案(5)|浏览(301)

我使用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=?")
        ;
    }
}

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>
lx0bsm1f

lx0bsm1f1#

这是因为spring默认的身份验证成功处理程序会寻找一个url来重定向。
我已经使用了下面,没有重定向发生.

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(appAuthenticationSuccessHandler());
kkih6yb8

kkih6yb82#

我遇到了这个问题,直到我在configure (HttpSecurity)方法中包含了.csrf().disable(),关闭了csrf-check。如果你没有关闭它,那么就提供csrf标记作为隐藏的表单字段。
......虽然我看到你把它关掉了

s1ag04yj

s1ag04yj3#

  • 与“表单操作”相同的“登录页面URL”
  • 显示代码

java配置:

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

超文本标记语言

<form action="/login.html" method="post">

您只需要通过http GET方法为“/login.html”编写控制器,将其余内容留给“spring”
文件https://docs.spring.io/spring-security/site/docs/5.3.6.RELEASE/reference/html5/#servlet-authentication-form
UsernamePasswordAuthenticationFilter通过http POST method/login.html匹配
我的英语不好,希望我能帮助你

9avjhtql

9avjhtql4#

我不知道这个问题是否总是活跃的,但如果这可以帮助别人...
对我有效的方法是

.formLogin()

.httpBasic();

在我的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();
}
vsikbqxv

vsikbqxv5#

使用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 {

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

}

}

请检查以下链接:http://www.baeldung.com/spring-security-redirect-login

相关问题