简体   繁体   English

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

[英]spring security HTTP Status 403 - Access Denied

Login is success but spring security blocking url even i given access to USER .登录成功,但 spring 安全阻止 url 即使我获得了对USER的访问权限。 How can i manage this thing?我该如何管理这件事?

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

LoginController.java登录控制器.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. Once Login success page redirected to welcome page but url is still localhost:8080/login instead of localhost:8080/welcome . 1.一旦登录成功页面重定向到欢迎页面,但 url 仍然是localhost:8080/login而不是localhost:8080/welcome

欢迎仪表板

2. After redirecting to URL localhost:8080/sales is it 403 Access denied. 2.重定向到URL localhost:8080/sales后是不是403 Access denied。

销售页面

What is spring security什么是 spring 安全性
Spring security is all about authentication and authorization, in your case you are missing authentication. Spring 安全性与身份验证和授权有关,在您的情况下,您缺少身份验证。 There is no configuration of authentication in your security configuration.您的安全配置中没有身份验证配置。 What you are missing is authentication filter for your spring security.您缺少的是 spring 安全性的身份验证过滤器。 Spring security provides default authentication filter UsernamePasswordAuthenticationFilter that can be configured by .formLogin() . Spring 安全提供默认身份验证过滤器UsernamePasswordAuthenticationFilter ,可以通过.formLogin()配置。 You can use default provided or you can define your own custom authentication filter(Implementation of UsernamePasswordAuthenticationFilter ).您可以使用提供的默认值,也可以定义自己的自定义身份验证过滤器( UsernamePasswordAuthenticationFilter的实现)。

Once authentication is success spring security will grant authorities for authenticated user.一旦身份验证成功,spring 安全性将为经过身份验证的用户授予权限。 If authentication is configured correctly, below configuration is responsible for authentication and granting authority如果认证配置正确,下面的配置负责认证和授予权限

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

Authenticated users each request will be passed through filter FilterSecurityInterceptor and it will verifies authority granted for authenticated user with authorization configured for resources as given in below code.经过身份验证的用户每个请求都将通过过滤器FilterSecurityInterceptor传递,它将验证为经过身份验证的用户授予的权限,并为资源配置了授权,如下面的代码所示。

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

You missed all this by not configuring authentication filter.您因未配置身份验证过滤器而错过了所有这些。
Now for making it simple use.formLogin() in your http configuration.现在,在您的 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() without any configuration provides default login page with username and password default form parameters.And after authentication it redirects to "/" If you want to provide your custom login page then use below configuration. .formLogin()没有任何配置提供默认登录页面,用户名和密码默认表单参数。身份验证后重定向到"/"如果您想提供自定义登录页面,请使用以下配置。

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

.loginPage("") - Your custom login page URL .loginPage("") - 您的自定义登录页面 URL
.usernameParameter("").passwordParameter("") - Your custom login form parameters .usernameParameter("").passwordParameter("") - 您的自定义登录表单参数
.defaultSuccessUrl("") - Page url after successful authentication .defaultSuccessUrl("") - 认证成功后的页面 url
.failureUrl("") - Page url after authentication failure .failureUrl("") - 身份验证失败后的页面 url

Note: You should not use "/login" POST method in your controller, Even though if you write, it will not be reached from spring security filter chain.注意:您不应该在 controller 中使用“/login” POST 方法,即使您编写,也不会从 spring 安全过滤器链到达。 As your configuration was wrong before, it was reaching before.由于您之前的配置是错误的,因此它之前已经到达。 Now you remove those from your controller and use conventional approach as mentioned above.现在您从 controller 中删除这些,并使用上述常规方法。

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

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