Previous Spring Cloud Gateway integration We explain how to integrate Spring cloud gateway
This article Source Address:
So then we want the gateway entrance can be integrated as a relevant certification authority, please refer to the specific integration process:
Spring Cloud Gateway to achieve access control
This integration module permissions, the general project to get the current logged-in user interface is one of the more frequent interface information to call. Here also reflects one of the benefits of using JWT way, the part of the user information has been cached in the token.
Based on the above information, we can start from the context of Security:
/**
* 获取用户token信息
* @return
*/
default Mono<JSONObject> getTokenInfo(){
Mono<JSONObject> baseUser = ReactiveSecurityContextHolder.getContext()
.switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
.map(SecurityContext::getAuthentication)
.map(Authentication::getPrincipal)
.map(jwt->{
Jwt jwtValue = null;
if(jwt instanceof Jwt){
jwtValue = (Jwt)jwt;
}
JSONObject tokenInfo = JSONObject.parseObject(JSONObject.toJSONString(jwtValue.getClaims()));
return tokenInfo;
});
return baseUser;
}
Such is the token to obtain information after decoding the entire JWT. Then we can get the information we want the user through the token.
/**
* 获取用户信息
* @return
*/
default Mono<BaseUser> getUserInfo(){
return getTokenInfo().map(token->token.getJSONObject(Constant.USER_INFO).toJavaObject(BaseUser.class));
}
Of course, usually for access control, we need to get the right information at the same time acquire the entire user's user interface so the final shaping as follows:
@Override
public Mono<UserResponse> getUserInfoByAccess() {
Mono<JSONObject> tokenInfo = getTokenInfo();
return tokenInfo.map(token->{
UserResponse userResponse = new UserResponse();
BaseUser baseUser = token.getJSONObject(Constant.USER_INFO).toJavaObject(BaseUser.class);
userResponse.setBaseUser(baseUser);
JSONArray array = token.getJSONArray("authorities");
//查询全部的权限
List<Permission> result = permissionUtil.getResultPermission(array);
if(!CollectionUtils.isEmpty(result)) {
userResponse.setAccess(result.stream().map(Permission::getAuthCode).collect(Collectors.toList()));
}
return userResponse;
});
}