spring security 角色认证无效 登录用户可以访问所有接口

新手上路,请多包涵

1.用户登录后,授予USER权限,却可以访问ADMIN权限的接口。

@Configuration
@EnableWebSecurity
@EnableResourceServer
//@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsServiceBean() throws Exception {
        return new UserDetailsServiceImpl();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsServiceBean());
    }

    /**
     * 用于支持 password 模式
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/user/login");
//                .antMatchers(HttpMethod.OPTIONS);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 将授权访问配置改为注解方式
         * @see LoginController#info()
         */
//        http.exceptionHandling()
//                .and()
//                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http.authorizeRequests()
                // 授权访问
                .antMatchers("/user/info").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("登录用户名:"+s);
        com.ho.logindemo.entity.User user = userMapper.selectUserByName(s);
        System.out.println(user);
        if (user!=null){
            System.out.println("找到用户!");
            List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
            GrantedAuthority grantedAuthority=new SimpleGrantedAuthority("USER");
            grantedAuthorities.add(grantedAuthority);
            return new User("test",user.getPassword(),grantedAuthorities);
        }else {
            System.out.println("未找到用户:"+s);
            return null;
        }
    }
}

访问ADMIN权限接口的日志

2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/info'; against '/user/login'
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token']
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/info'; against '/oauth/token'
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/token_key']
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/info'; against '/oauth/token_key'
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/oauth/check_token']
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/info'; against '/oauth/check_token'
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2019-09-21 23:40:03.001 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', GET]
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Checking match of request : '/user/info'; against '/logout'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', POST]
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/info' doesn't match 'POST /logout'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', PUT]
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/info' doesn't match 'PUT /logout'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : Trying to match using Ant [pattern='/logout', DELETE]
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher  : Request 'GET /user/info' doesn't match 'DELETE /logout'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher  : No matches found
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2019-09-21 23:40:03.002 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.o.p.a.BearerTokenExtractor         : Token not found in headers. Trying request parameters.
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] p.a.OAuth2AuthenticationProcessingFilter : Authentication success: org.springframework.security.oauth2.provider.OAuth2Authentication@b13c9ad6: Principal: org.springframework.security.core.userdetails.User@364492: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: USER
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.AnonymousAuthenticationFilter  : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.oauth2.provider.OAuth2Authentication@b13c9ad6: Principal: org.springframework.security.core.userdetails.User@364492: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: USER'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy@259b85d6
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Secure object: FilterInvocation: URL: /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f; Attributes: [#oauth2.throwOnError(authenticated)]
2019-09-21 23:40:03.003 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Previously Authenticated: org.springframework.security.oauth2.provider.OAuth2Authentication@b13c9ad6: Principal: org.springframework.security.core.userdetails.User@364492: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: USER
2019-09-21 23:40:03.004 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.access.vote.AffirmativeBased       : Voter: org.springframework.security.web.access.expression.WebExpressionVoter@1acf40d9, returned: 1
2019-09-21 23:40:03.004 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : Authorization successful
2019-09-21 23:40:03.004 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.i.FilterSecurityInterceptor    : RunAsManager did not change Authentication object
2019-09-21 23:40:03.004 DEBUG 17268 --- [nio-8080-exec-5] o.s.security.web.FilterChainProxy        : /user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f reached end of additional filter chain; proceeding with original chain
2019-09-21 23:40:03.004 DEBUG 17268 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : GET "/user/info?access_token=3e0a7ad2-edaf-45fe-be6e-31b9a35daf3f", parameters={masked}
2019-09-21 23:40:03.005 DEBUG 17268 --- [nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public java.util.Map<java.lang.String, java.lang.Object> com.ho.logindemo.controller.LoginController.info()
USER
2019-09-21 23:40:03.006 DEBUG 17268 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Using 'application/json', given [*/*] and supported [application/json, application/*+json, application/json, application/*+json]
2019-09-21 23:40:03.006 DEBUG 17268 --- [nio-8080-exec-5] m.m.a.RequestResponseBodyMethodProcessor : Writing [{msg=查询成功, code=200, data={name=test, avatar=666666666}}]
2019-09-21 23:40:03.007 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@39ed628e
2019-09-21 23:40:03.008 DEBUG 17268 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet        : Completed 200 OK
2019-09-21 23:40:03.008 DEBUG 17268 --- [nio-8080-exec-5] o.s.s.w.a.ExceptionTranslationFilter     : Chain processed normally
2019-09-21 23:40:03.008 DEBUG 17268 --- [nio-8080-exec-5] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

用户授权没问题

User@364492: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: remoteAddress=0:0:0:0:0:0:0:1, tokenType=BearertokenValue=<TOKEN>; Granted Authorities: USER

网上搜了一圈没有解决问题,不知道哪个环节出问题了,求大佬赐教
完整demo:链接: https://pan.baidu.com/s/1L_R7... 提取码: 49up

阅读 5.4k
1 个回答
新手上路,请多包涵

被注释掉的那一行代码的问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题