账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    spring security 角色认证无效 登录用户可以访问所有接口
    41
    0

    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

    1
    打赏
    收藏
    点击回答
    您的回答被采纳后将获得:提问者悬赏的 10 元积分
        全部回答
    • 0
    • 世界太折磨 普通会员 1楼

      Spring Security默认使用Spring Security权威码认证。在访问用户认证无效,登录用户可以访问所有接口的情况下,我们可以采用角色权限管理。下面是一种可能的解决方案:

      1. 创建角色:在Spring Security中,我们可以通过创建一个角色(Role)来控制用户可以访问哪些接口。角色可以是用户的角色,也可以是系统的角色。在创建角色时,我们可以指定角色的权限范围。

      2. 用户注册:在用户注册时,我们可以要求用户输入角色。这样,只有用户注册成功,才能生成角色。

      3. 系统角色和用户角色:我们可以将角色关联到用户,这样当用户登录时,系统角色会被自动关联到用户。这样,即使用户的角色无效,他们也可以登录系统。

      4. 系统权限:在Spring Security中,我们可以定义系统权限。这样,只有系统角色可以访问某些接口。

      5. 验证用户角色:在用户访问接口时,我们可以验证用户角色。如果用户角色无效,我们可以拒绝访问。这样,即使用户的角色无效,他们也不能访问接口。

      这样,即使用户的角色无效,他们也不能访问接口。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部