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

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

LoginController.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 .

welcome dashboard

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

sales page

最佳答案

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

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

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

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

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

由于没有配置身份验证过滤器,您错过了这一切。
现在为了让它变得简单,请在 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();
}

.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 Security过滤器链中到达。由于之前的配置错误,所以之前就到达了!现在,您从 Controller 中删除它们并使用上面提到的传统方法。

关于java - spring security HTTP状态403-访问被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58098618/

相关文章:

jquery - 发送 json 到服务器 spring 3.x

java - java中如何将字符串值转换为二进制值

java - 如何在Java中创建一个简单的连接表?

java - Spring LDAP 基本用法

java - 在 Spring Boot 应用程序中加载第三方 jar 的问题

java - 异常: org. springframework.beans.factory.BeanCreationException:创建名称为 'org.springframework.security.filterChains'的bean时出错

tomcat - 将 Spring MVC 3 应用程序部署到 tomcat

方法中的 Java 隐式 "this"参数?

java - 来自 Java 应用程序的 Activex?

java - 如何配置 swagger 来处理自定义 Controller 级路径变量注释?