繁体   English   中英

spring 安全 HTTP 状态 403 - 访问被拒绝

[英]spring security HTTP Status 403 - Access Denied

登录成功,但 spring 安全阻止 url 即使我获得了对USER的访问权限。 我该如何管理这件事?

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

登录控制器.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";
    }
}

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

欢迎仪表板

2.重定向到URL localhost:8080/sales后是不是403 Access denied。

销售页面

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

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

auth.inMemoryAuthentication().withUser("sahil").password("123")
                .roles("ADMIN","USER");

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

.antMatchers("/welcome","/inventory/**","/sales/**").access("hasRole('USER')")

您因未配置身份验证过滤器而错过了所有这些。
现在,在您的 http 配置中使其变得简单 use.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();
}

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

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

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

注意:您不应该在 controller 中使用“/login” POST 方法,即使您编写,也不会从 spring 安全过滤器链到达。 由于您之前的配置是错误的,因此它之前已经到达。 现在您从 controller 中删除这些,并使用上述常规方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM