java - 我可以在 Spring Security 中进行身份验证吗?

标签 java spring-security

我正在使用 Spring Security 根据角色对用户进行身份验证。对 /** 进行身份验证会给出:

Page load failed with error: too many HTTP redirects

错误且未显示登录页面。

  protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
            .antMatchers("/login*").authenticated()
            .antMatchers("/**").authenticated()
            .and()
            .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
            .usernameParameter("username").passwordParameter("password")
            .and()
            .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
            .and()
            .exceptionHandling().accessDeniedPage("/accessDenied")
            .and()
            .csrf();
        }

但如果我这样做:

protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers("/login").authenticated()
        .antMatchers("/").authenticated()
        .and()
        .formLogin().loginPage("/login").failureUrl("/login?error").defaultSuccessUrl("/welcome")
        .usernameParameter("username").passwordParameter("password")
        .and()
        .logout().logoutSuccessUrl("/login?logout").logoutUrl("/login?logout")
        .and()
        .exceptionHandling().accessDeniedPage("/accessDenied")
        .and()
        .csrf();
    }

此代码对 /** URL 进行身份验证有什么问题?

最佳答案

未经身份验证的用户无法访问您的登录页面:

.antMatchers("/login*").authenticated()

因此 Spring Security 重定向到您的登录页面,该页面又重定向到您的日志页面,...

您必须允许未经身份验证的用户访问您的登录页面,请参阅Spring Security Reference :

While the automatically generated log in page is convenient to get up and running quickly, most applications will want to provide their own log in page. To do so we can update our configuration as seen below:

protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests()
          .anyRequest().authenticated()
          .and()
      .formLogin()
          .loginPage("/login") 1
          .permitAll();        2
}

1 The updated configuration specifies the location of the log in page.

2 We must grant all users (i.e. unauthenticated users) access to our log in page. The formLogin().permitAll() method allows granting access to all users for all URLs associated with form based log in.

如果删除通配符 (*),则未经身份验证的用户都可以访问除 login/ 之外的所有页面。

关于java - 我可以在 Spring Security 中进行身份验证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39579881/

相关文章:

rest - 如何在 Spring Boot Web 应用程序中保护 REST API?

java - Spring Security 安全自定义页面

java - Spring-Security-OAuth2 中的 grant_type

java - 如何使用 Spring Roo 创建基础域对象?

java - 在 Google Vision API 中使用 Java 时如何修复 "Error: Invalid GCS Path Specified"?

javascript - 使用服务器 Java 和 Javascript 客户端的 Apache Thrift 数组

java - 方法 clear() 未为类型 ShoppingCart 定义

spring-boot - 资源服务器上的 Spring Boot OAuth2 自定义角色

Java 容器 .contains 问题

javascript - 使用 sockjs 和 stomp 在/信息请求期间没有 cookie