首页 > 解决方案 > Spring Security - 身份验证问题

问题描述

我正在开发一个 Web 应用程序并选择使用 Spring Security。这个想法是让用户通过身份验证以查看主页,如果用户未通过身份验证,他们将被重定向到登录页面。此登录页面还显示了一个注册表单的链接,这部分工作正常。

但是,我在尝试允许用户通过注册链接注册时遇到了问题。如果用户未通过身份验证,则无法访问注册表单的链接(“showRegistrationForm”)

任何人都可以提供有关为什么会发生这种情况的见解吗?我在下面的 SecurityConfig 中包含了代码片段

    @Override
protected void configure(HttpSecurity http) throws Exception {

    //Restrict Access based on the Intercepted Servlet Request 

    http.authorizeRequests()
    .antMatchers("/resources/**", "/register").permitAll()
    .anyRequest().authenticated()
    .antMatchers("/").hasRole("EMPLOYEE")
    .antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
    .antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
    .antMatchers("/delete/**").hasRole("ADMIN")
    .and()
    .formLogin()
// Show the custom form created for the below request mappings
        .loginPage("/showSonyaLoginPage")
        .loginProcessingUrl("/authenticateTheUser")
// No need to be logged in to see the login page
        .permitAll()
    .and()
// No need to be logged in to see the logout button.
    .logout().permitAll()
    .and()
    .exceptionHandling().accessDeniedPage("/access-denied");    
}

标签: spring-bootspring-security

解决方案


更改如下代码:

@Override
protected void configure(HttpSecurity http) throws Exception {


    // Restrict Access based on the Intercepted Servlet Request 

    http.authorizeRequests()
        .antMatchers("/showRegistrationForm/").permitAll()
        .anyRequest().authenticated()
        .antMatchers("/").hasRole("EMPLOYEE")
        .antMatchers("/resources/").permitAll()
        .antMatchers("/showForm/**").hasAnyRole("EMPLOYEE","MANAGER", "ADMIN")
        .antMatchers("/save/**").hasAnyRole("MANAGER", "ADMIN")
        .antMatchers("/delete/**").hasRole("ADMIN")
        .and()
        .formLogin()
    // Show the custom form created for the below request mappings
            .loginPage("/showSonyaLoginPage")
            .loginProcessingUrl("/authenticateTheUser")
    // No need to be logged in to see the login page
            .permitAll()
        .and()
    // No need to be logged in to see the logout button.
        .logout().permitAll()
        .and()
        .exceptionHandling().accessDeniedPage("/access-denied");    
}

向下移动以下代码:

anyRequest().authenticated()

推荐阅读