forked from kidgrow-microservices-platform

克 刘
2020-04-10 1199db2b4050475a84a95cf6b57435caffb036db
kidgrow-springcloud/kidgrow-springcloud-zuul/src/main/java/com/kidgrow/zuul/auth/Oauth2AuthSuccessHandler.java
@@ -2,7 +2,9 @@
import cn.hutool.core.collection.CollectionUtil;
import com.kidgrow.common.constant.SecurityConstants;
import com.kidgrow.common.model.SysOrganization;
import com.kidgrow.common.model.SysUser;
import lombok.SneakyThrows;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
@@ -13,6 +15,9 @@
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.net.URLEncoder;
import java.util.List;
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
@@ -22,23 +27,34 @@
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler {
    @SneakyThrows
    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        MultiValueMap<String, String> headerValues = new LinkedMultiValueMap(4);
        Object principal = authentication.getPrincipal();
        String tenantId="";
        //客户端模式只返回一个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());
            List<SysOrganization> organizations = (List<SysOrganization>)user.getOrganizations();
            //如果有组织架构
            if(organizations!=null && organizations.size()==2){
                headerValues.add(SecurityConstants.USER_ORG_ID_HEADER,String.valueOf(organizations.get(0).getId()));
                headerValues.add(SecurityConstants.USER_ORG_NAME_HEADER, URLEncoder.encode(organizations.get(0).getOrgName(),"UTF-8"));
                headerValues.add(SecurityConstants.USER_DEP_ID_HEADER,String.valueOf(organizations.get(1).getId()));
                headerValues.add(SecurityConstants.USER_DEP_NAME_HEADER,URLEncoder.encode(organizations.get(1).getOrgName(),"UTF-8"));
                tenantId=String.valueOf(organizations.get(0).getId());
            }
        }
        OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
        String clientId = oauth2Authentication.getOAuth2Request().getClientId();
        String tenantId="";
        //保存租户id,租户id根据业务尽进行替换
        switch (clientId){
            case "hospital":
                tenantId="1";
                tenantId=tenantId;
                break;
            case "webApp":
                tenantId="webApp";