forked from kidgrow-microservices-platform

zhaoxiaohao
2020-05-22 f21c78ae0e3c410c6ba5be77277b5b491aca3af1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.kidgrow.common.filter;
 
import cn.hutool.core.util.StrUtil;
import com.kidgrow.common.constant.SecurityConstants;
import com.kidgrow.common.context.ClientContextHolder;
import com.kidgrow.common.context.TenantContextHolder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.web.filter.OncePerRequestFilter;
 
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * 石家庄喜高科技有限责任公司 版权所有 © Copyright 2020<br>
 *
 * @Description: 租户过滤器<br>
 * @Project: <br>
 * @CreateDate: Created in 2020/2/27 15:02 <br>
 * @Author: <a href="4345453@kidgrow.com">liuke</a>
 */
@ConditionalOnClass(Filter.class)
public class TenantFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
            String clientId = request.getHeader(SecurityConstants.CLIENT_HEADER);
            //保存ClientID
            if (StrUtil.isNotEmpty(clientId)) {
                ClientContextHolder.setClient(clientId);
            }
 
            //优先获取请求参数中的tenantId值
//            String tenantId = request.getParameter(CommonConstant.TENANT_ID_PARAM);
            String tenantId = "";
            if (StrUtil.isEmpty(tenantId)) {
                tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
            }
            //保存租户id
            if (StrUtil.isNotEmpty(tenantId)) {
                TenantContextHolder.setTenant(tenantId);
            }
 
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }
}