优化网关认证信息传递逻辑,适配oauth2的客户端模式

This commit is contained in:
zlt
2019-11-19 20:58:30 +08:00
parent 0ed68b9fe7
commit f05bb8741d
2 changed files with 21 additions and 15 deletions
@@ -8,6 +8,8 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@@ -23,19 +25,23 @@ import reactor.core.publisher.Mono;
public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
@Override
public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
SysUser user = (SysUser)authentication.getPrincipal();
Long userId = user.getId();
String username = user.getUsername();
MultiValueMap<String, String> headerValues = new LinkedMultiValueMap(4);
Object principal = authentication.getPrincipal();
//客户端模式只返回一个clientId
if (principal instanceof SysUser) {
SysUser user = (SysUser)authentication.getPrincipal();
headerValues.add(SecurityConstants.USER_ID_HEADER, String.valueOf(user.getId()));
headerValues.add(SecurityConstants.USER_HEADER, user.getUsername());
}
OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
String clientId = oauth2Authentication.getOAuth2Request().getClientId();
headerValues.add(SecurityConstants.TENANT_HEADER, clientId);
headerValues.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
ServerWebExchange exchange = webFilterExchange.getExchange();
ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate()
.headers(h -> {
h.add(SecurityConstants.USER_ID_HEADER, String.valueOf(userId));
h.add(SecurityConstants.USER_HEADER, username);
h.add(SecurityConstants.TENANT_HEADER, clientId);
h.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ","));
h.addAll(headerValues);
})
.build();