在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問(wèn)答/Java/ 有一個(gè)Spring security相關(guān)的問(wèn)題(動(dòng)態(tài)授權(quán))

有一個(gè)Spring security相關(guān)的問(wèn)題(動(dòng)態(tài)授權(quán))

一般的做法,在controller層,已經(jīng)把權(quán)限指定到對(duì)應(yīng)的方法上了,如:

  • PreAuthorize
  • Secured
  • RolesAllowed

但是,這樣方式在調(diào)整權(quán)限的時(shí)候要改代碼,最討厭了,一邊寫(xiě)代碼,還要一邊想著該給個(gè)什么樣合適的權(quán)限。

這樣,預(yù)期是編碼的人完成接口后,在程序啟動(dòng)后,從DB中查詢出來(lái)URL/或controller層方法對(duì)應(yīng)的角色,然后直接調(diào)用Spring Security相關(guān)的權(quán)限掃描(如上述注解的初始處理),然后把權(quán)限加載進(jìn)去。后續(xù)驗(yàn)證用戶角色即可。

那么問(wèn)題來(lái)了,如何找到PreAuthorize,Secured,RolesAllowed這些注解的初始化方法,而這些方法有沒(méi)有提供公開(kāi)的接口供程序調(diào)用?

有人能指點(diǎn)下,不勝感激。

回答
編輯回答
陪我終

暫時(shí)通過(guò)AntPathMatcher遍歷匹配了內(nèi)存中的RequestMapper的path>自定義注解的接口ID,然后從DB里查找到對(duì)應(yīng)的roles與用戶的roles取交集,實(shí)現(xiàn)了功能。
如果數(shù)據(jù)量大了的話,可能要走AOP/ControllerAdvise攔截Controller層,然后讀自定義注解去查詢角色并與用戶的比對(duì)。。。

2018年5月30日 07:31
編輯回答
萌小萌

這里在 springboot 使用 security 框架。

具體過(guò)程如下:

class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomAuthenticationProvider authProvider
   

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 自定義認(rèn)證過(guò)程
        auth.authenticationProvider(authProvider)
    }
}

@Component
class CustomAuthenticationProvider implements AuthenticationProvider {

  
    @Override
    Authentication authenticate(Authentication authentication) throws AuthenticationException {
       
       // 認(rèn)證過(guò)程...
       
       // 認(rèn)證成功生成 token ,關(guān)鍵在于這個(gè) SimpleGrantedAuthority
       List list = new ArrayList();
       list.put(new SimpleGrantedAuthority("Expert"))
       return new UsernamePasswordAuthenticationToken(session, token,list )
   

    }
}

// 這里的 Expert 對(duì)應(yīng)的就是 SimpleGrantedAuthority 類里的 role
@PostMapping("/add")
@PreAuthorize("hasAuthority('Expert')")
Response<?> release(@RequestBody Request req) {
   //....
}
2017年2月10日 18:02