解决无法获取权限的问题
问题
授权服务器是OAuth2的,对于系统本身用户分配了client,id为browser,scope为all,在资源服务器中获取到的authorities为scope而不是用户本身的系统内权限。
解决方案
授权服务器
授权服务器默认存储一个client为系统内用户集合,scope为all
,实现UserDetailsService
接口复写loadUserByUsername
方法,将系统内权限传递给springsecurity,最后塞入jwt消息中
/**
* 客户端详情信息在这里进行初始化,你能够把客户端详情信息写死在这里或者是通过数据库来存储调取详情信息
* @param clients
* @throws Exception
*/
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient(OAuth2_Client.BROWSER.getClient_id())
.authorizedGrantTypes(OAuth2_Client.BROWSER.getGrant_type())
.secret(OAuth2_Client.BROWSER.getClient_secret())
.scopes(OAuth2_Client.BROWSER.getClient_scope())
.authorities("admin","user")
.accessTokenValiditySeconds(12*60*60);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("load user by username " + username);
Result<User> userRes = userFeignService.getUserDetail(username);
if (ResultCode.USER_NOT_EXIST.getCode().equals(userRes.getCode())) {
throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
}
User user = userRes.getData();
log.info("load user by username success");
return new CustomerUserDetails(user);
}
生成的JWT消息示例
{
alg: "RS256",
typ: "JWT"
}.
{
sub: "admin",
exp: 1608031046,
authorities: [
"ROLE_admin",
"ROLE_user"