首页 > 解决方案 > Spring URL 授权失败,用户在 WebExpressionV 中不是匿名的

问题描述

我正在使用我自己的 UserDetailService 构建一个简单的 Spring 启动应用程序,该应用程序使用 Spring Security 来学习,它返回一个用户对象进行身份验证。我有以下代码来配置授权,但是当我使用自定义 UserDetailService 时,授权失败,并且同样适用于 inmemoryAuthentication 或 JDbcAuthentication。

我遇到的问题是,对于需要权限的用户,我总是会收到 403 禁止错误,而我可以轻松访问主页,因此身份验证有效,但授权存在一些问题。

我已经列出了错误和代码,希望有人能提供一些线索。我尝试了许多不同的方法,例如禁用 csrf、使用权限而不是角色,反之亦然等,但似乎没有任何效果。Spring的版本是2.3.1

日志显示以下错误

2020-07-27 14:49:43.128 DEBUG 13952 --- [http-nio-8091-exec-5] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@50390f54, returned: -1
2020-07-27 14:49:43.129 DEBUG 13952 --- [http-nio-8091-exec-5] o.s.s.w.a.ExceptionTranslationFilter     : Access is denied (user is not anonymous); delegating to AccessDeniedHandler

org.springframework.security.access.AccessDeniedException: Access is denied

配置方法和自定义 Userdetailservice 的代码如下

 /* The configure methods of the class SecurityConfigurator extends WebSecurityConfigurerAdapter */
    @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
              auth.userDetailsService(userDetailsService);
    }
    
    @Override
        protected void configure(HttpSecurity http) throws Exception {
            //add most restrictive at the top.
            http.authorizeRequests()
                    .antMatchers("/admin").hasRole("ADMIN")
                    //.hasAuthority("USERS")
                    .antMatchers("/user").hasAnyRole("ADMIN", "USERS")
                    //.hasAnyAuthority("ADMIN","USERS")
                    .antMatchers("/**").permitAll()
                    .and().formLogin();
    
        }
/* My UserDetailService is simple that it just returns an object of hardcoded UserDetails */

    @Service
    public class MyUserDetailsService implements UserDetailsService {
    
        @Override
        public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
            UserDetails user = new MyUserDetails(s);
            return user;
        }
    }

标签: springspring-securityauthorizationbasic-authentication

解决方案


推荐阅读