Spring安全 - 无法访问登录页面

时间:2018-04-30 21:26:17

标签: 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");
    }
}

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

  

页面未正确重定向。 Firefox已经检测到了   服务器正在以一种方式重定向该地址的请求   永远不会完成此问题有时可能是由禁用或导致的   拒绝接受cookies。

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

有谁能告诉我怎么解决这个问题?

2 个答案:

答案 0 :(得分:2)

之后

    .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();
}

答案 1 :(得分:1)

存在配置问题。

您有拦截网址"/*"ROLE_USER'的模式,这意味着如果用户未获得授权,它将被重定向到login页面。

应用程序上下文解析了login页面,发现/login页面匹配"/*"模式,应该为ROLE_USER拦截和验证。显然,未经身份验证的用户没有ROLE_USER并重定向到/login页面并重新定位。

允许未经通信的用户访问登录页面应该可以解决问题:

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

注意订单。应首先编写更具体的过滤器,否则它们将被更宽的过滤器“遮蔽”并被忽略。

permitAll()可以应用于login页面,直接省略第一个匹配器,如已经提出的那样:

.loginPage("/login").permitAll();
相关问题