有一个Spring security相关的问题(动态授权)

一般的做法,在controller层,已经把权限指定到对应的方法上了,如:

  • PreAuthorize
  • Secured
  • RolesAllowed

但是,这样方式在调整权限的时候要改代码,最讨厌了,一边写代码,还要一边想着该给个什么样合适的权限。

这样,预期是编码的人完成接口后,在程序启动后,从DB中查询出来URL/或controller层方法对应的角色,然后直接调用Spring Security相关的权限扫描(如上述注解的初始处理),然后把权限加载进去。后续验证用户角色即可。

那么问题来了,如何找到PreAuthorize,Secured,RolesAllowed这些注解的初始化方法,而这些方法有没有提供公开的接口供程序调用?

有人能指点下,不胜感激。

阅读 2.5k
2 个回答

这里在 springboot 使用 security 框架。

具体过程如下:

class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider
   

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 自定义认证过程
        auth.authenticationProvider(authProvider)
    }
}

@Component
class CustomAuthenticationProvider implements AuthenticationProvider {

  
    @Override
    Authentication authenticate(Authentication authentication) throws AuthenticationException {
       
       // 认证过程...
       
       // 认证成功生成 token ,关键在于这个 SimpleGrantedAuthority
       List list = new ArrayList();
       list.put(new SimpleGrantedAuthority("Expert"))
       return new UsernamePasswordAuthenticationToken(session, token,list )
   

    }
}

// 这里的 Expert 对应的就是 SimpleGrantedAuthority 类里的 role
@PostMapping("/add")
@PreAuthorize("hasAuthority('Expert')")
Response<?> release(@RequestBody Request req) {
   //....
}

暂时通过AntPathMatcher遍历匹配了内存中的RequestMapper的path>自定义注解的接口ID,然后从DB里查找到对应的roles与用户的roles取交集,实现了功能。
如果数据量大了的话,可能要走AOP/ControllerAdvise拦截Controller层,然后读自定义注解去查询角色并与用户的比对。。。

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