CeDo
2021-05-10 458a590d905246081332cba18997c9b5c68aa725
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package com.panzhihua.zuul.filters;
 
import com.alibaba.fastjson.JSONArray;
import com.panzhihua.common.constants.*;
import com.panzhihua.common.model.vos.R;
import com.panzhihua.common.utlis.JWTTokenUtil;
import com.panzhihua.common.utlis.ResultUtil;
import com.panzhihua.zuul.config.RealNamedConfig;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
 
/**
 * @program: springcloud_k8s_panzhihuazhihuishequ
 * @description: 小程序权限验证
 * @author: huang.hongfa weixin hhf9596 qq 959656820
 * @create: 2020-11-25 16:35
 **/
@Component
public class AppletAuthenticationFilter implements Filter {
    private StringRedisTemplate stringRedisTemplate;
 
    @Autowired
    private RealNamedConfig realNamedConfig;
 
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    /**
     * 用户是否登录校验
     *
     * @param servletRequest  请求
     * @param servletResponse 返回
     * @param filterChain     过滤器链条
     * @throws IOException      io
     * @throws ServletException servlet
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        SafeboxRequestWrapper safeboxRequestWrapper = new SafeboxRequestWrapper(request);
        HttpServletResponse response = (HttpServletResponse) servletResponse;
 
        // 获取请求头中JWT的Token
        String tokenHeader = request.getHeader(TokenConstant.TOKEN_HEADER);
        if (null != tokenHeader && tokenHeader.startsWith(TokenConstant.TOKEN_PRE)) {
            String token = tokenHeader.replace(TokenConstant.TOKEN_PRE, "");
 
            // token解析
            Claims claims = JWTTokenUtil.getClaimsFromToken(token);
            String username = claims.getSubject();
            int type = (Integer) claims.get("type");
            if (1 == type) {//小程序用户统一角色
                String requestURI = request.getRequestURI();
                String requestMethod = request.getMethod().toLowerCase();
 
                ServletContext context = request.getServletContext();
                ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
                stringRedisTemplate = ctx.getBean(StringRedisTemplate.class);
                ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
                String appletUserRoleKey = SecurityConstants.ROLE_APPLETS_USER + username;
                Boolean userHasRole = stringRedisTemplate.hasKey(appletUserRoleKey);
 
                boolean needCheck = false;
                List<String> checkedUrl = realNamedConfig.getVerify();
                checkedUrl = checkedUrl!=null?checkedUrl:new ArrayList<>();
                for (int i = 0; i < checkedUrl.size(); i++) {
                    String url = checkedUrl.get(i);
                    if (url.toLowerCase().startsWith(requestMethod) && url.endsWith(requestURI)) {
                        needCheck = true;
                    } else {
                        continue;
                    }
                }
                if (needCheck) {
                    if (userHasRole) {
                        boolean userHashRight = false;
                        try {
                            String roles = valueOperations.get(appletUserRoleKey);
                            List<SimpleGrantedAuthority> authorities = JSONArray.parseArray(roles, SimpleGrantedAuthority.class);
                            if (authorities != null && authorities.size() > 0) {
                                AtomicBoolean userHasRightRole = new AtomicBoolean(false);
                                authorities.forEach(authority -> {
                                    if (authority.getAuthority().equals(SecurityConstants.ROLE_APPLETS_REAL_NAMED)) {
                                        userHasRightRole.set(true);
                                    }
                                });
                                if (userHasRightRole.get()) {
                                    //用户包含“已实名”角色,则放行 什么也不做
                                    userHashRight = true;
                                }
                            }
                        } catch (Exception e) {
                            userHashRight = false;
                        }
 
                        if (!userHashRight) {
                            ResultUtil.responseJson(response, R.fail(HttpStatus.FORBIDDEN, "用户未实名"));
                            return;
                        }
                    }else{
                        ResultUtil.responseJson(response, R.fail(HttpStatus.FORBIDDEN, "用户未实名"));
                        return;
                    }
 
                }
            }
        }
        filterChain.doFilter(safeboxRequestWrapper, response);
    }
 
    @Override
    public void destroy() {
 
    }
}