java - Spring security - 无法进入登录页面

标签 java spring spring-security

这是我的 spring 安全配置类:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery(
                        "select nickname,password, true from client where nickname=?")
                .authoritiesByUsernameQuery(
                        "select username, role from user_roles where username=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/*")
                .access("hasRole('ROLE_USER')");
        http.formLogin()
                .defaultSuccessUrl("/", true)
                .loginPage("/login");
    }
}

当我尝试打开网页时,出现此错误:

The page isn’t redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete. This problem can sometimes be caused by disabling or refusing to accept cookies.

当我删除配置方法时,一切正常。

谁能告诉我如何解决这个问题?

最佳答案

之后

    .loginPage("/login")

你应该添加

    .permitAll();

执行上述操作应该可以解决您的问题。至于为什么会发生这种情况,是因为您的 loginPage 要求用户进行身份验证,这会导致 Spring 将用户重定向到 loginPage,并从那里循环。 Firefox 足够好,可以在检测到该行为时停止请求。

我还建议您使用 .anyRequest() 而不是 .antMatchers("/*")

最终结果应该是这样的

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest()
            .access("hasRole('ROLE_USER')")
        .and()
        .formLogin()
            .defaultSuccessUrl("/", true)
            .loginPage("/login")
            .permitAll();
}

关于java - Spring security - 无法进入登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50108442/

相关文章:

java - 初始化数组是否保留其在 C/C++ 和类似语言中的顺序?

具有通用类类型的 Java 反射 getDeclaredMethod()

java - Spring MVC : @Value annotation with final variable

java - 优化 Spring Boot JPA 查询

java - Spring boot 2.1 error.html 页面不显示

spring - 无需通过每个 Controller 即可获取用户 ID

java - 使用 maven 存储库将 java 库添加到 Android Studio 项目

java - Spring JPA Crud 存储库保存不返回 UUID 字段

java - Spring REST security - 以不同方式保护不同的 URL

java - (Hibernate)Session.close()和releaseSession(Session)之间的区别