spring security HTTP状态403-访问被拒绝

Sah*_*hil 1 java spring spring-mvc spring-security access-denied

登录成功,但即使我授予了USER 的访问权限,Spring Security 也会阻止 url 。我该如何管理这件事?

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
            throws Exception {
        auth.inMemoryAuthentication().withUser("sahil").password("123")
                .roles("ADMIN","USER");
    }

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

        http.authorizeRequests()
        .antMatchers("/login").permitAll()
        .antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")
        .and()
        .csrf().disable();
    }
Run Code Online (Sandbox Code Playgroud)

登录控制器.java

    @Controller
public class LoginController {

    @RequestMapping(value = { "/", "/login" }, method = RequestMethod.GET)
    public String showLoginPage() {
        return "login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String handleUserLogin(ModelMap model, @RequestParam String name, @RequestParam String password) {
        if (!service.validateUser(name, password)) {
            model.put("errorMsg", "Invalid Credential");
            return "login";
        }
        System.out.println("principal : " + getLoggedInUserName());
        model.put("name", name);
        model.put("password", password);
        return "welcome";
    }

    private String getLoggedInUserName() {

        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (principal instanceof UserDetails) {
            System.out.println("in if");
          return  ((UserDetails)principal).getUsername();

        } else {
            System.out.println("in else");
         return principal.toString();

        }
    }

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String showWelcomeDashboard() {
        return "welcome";
    }
}
Run Code Online (Sandbox Code Playgroud)

1. 一旦登录成功页面重定向到欢迎页面,但 url 仍然是localhost:8080/login而不是localhost:8080/welcome

欢迎仪表板

2.重定向到 URL localhost:8080/sales后是否出现 403 访问被拒绝。

销售页面

Pra*_*ngi 5

什么是 Spring Security
Spring Security 是关于身份验证和授权的,在您的情况下,您缺少身份验证。您的安全配置中没有身份验证配置。您缺少的是 Spring Security 的身份验证过滤器。Spring security 提供了默认的身份验证过滤器UsernamePasswordAuthenticationFilter,可以通过.formLogin(). 您可以使用提供的默认值,也可以定义自己的自定义身份验证过滤器(实现UsernamePasswordAuthenticationFilter)。

一旦身份验证成功,Spring Security 将为经过身份验证的用户授予权限。如果认证配置正确,下面的配置负责认证和授予权限

auth.inMemoryAuthentication().withUser("sahil").password("123")
                .roles("ADMIN","USER");
Run Code Online (Sandbox Code Playgroud)

经过身份验证的用户的每个请求都将通过过滤器FilterSecurityInterceptor,并且它将验证为经过身份验证的用户授予的权限,并为资源配置授权,如下面的代码所示。

.antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")
Run Code Online (Sandbox Code Playgroud)

由于没有配置身份验证过滤器,您错过了这一切。
现在为了让它变得简单,请在 http 配置中使用.formLogin() 。

@Override
protected void configure(final HttpSecurity http) throws Exception
{
    http
    .authorizeRequests()
        .antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")
    .and().exceptionHandling()
        .accessDeniedPage("/403")
    .and().formLogin()
    .and().logout()
        .logoutSuccessUrl("/login?logout=true")
        .invalidateHttpSession(true)
    .and()
        .csrf()
            .disable();
}
Run Code Online (Sandbox Code Playgroud)

.formLogin()无需任何配置,即可提供带有用户名和密码默认表单参数的默认登录页面。身份验证后,它会重定向到"/"如果您想提供自定义登录页面,请使用以下配置。

.and().formLogin()
       .loginPage("/login")
       .usernameParameter("email").passwordParameter("password")
       .defaultSuccessUrl("/app/user/dashboard")
       .failureUrl("/login?error=true")
Run Code Online (Sandbox Code Playgroud)

.loginPage("")- 您的自定义登录页面 URL
.usernameParameter("").passwordParameter("")- 您的自定义登录表单参数
.defaultSuccessUrl("")- 身份验证成功后的页面 url
.failureUrl("")- 身份验证失败后的页面 url

注意:您不应该在控制器中使用“/login”POST 方法,即使您编写,也不会从 spring security 过滤器链到达它。由于之前的配置错误,所以之前就到达了!现在,您从控制器中删除它们并使用上面提到的传统方法。