yangys
2025-08-04 96481362fed4eab7b96cc9016ece1917b43bbcc5
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
 * BladeX Commercial License Agreement
 * Copyright (c) 2018-2099, https://bladex.cn. All rights reserved.
 * <p>
 * Use of this software is governed by the Commercial License Agreement
 * obtained after purchasing a license from BladeX.
 * <p>
 * 1. This software is for development use only under a valid license
 * from BladeX.
 * <p>
 * 2. Redistribution of this software's source code to any third party
 * without a commercial license is strictly prohibited.
 * <p>
 * 3. Licensees may copyright their own code but cannot use segments
 * from this software for such purposes. Copyright of this software
 * remains with BladeX.
 * <p>
 * Using this software signifies agreement to this License, and the software
 * must not be used for illegal purposes.
 * <p>
 * THIS SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY. The author is
 * not liable for any claims arising from secondary or illegal development.
 * <p>
 * Author: Chill Zhuang (bladejava@qq.com)
 */
package org.springblade.auth.handler;
 
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.cache.CacheNames;
import org.springblade.common.constant.TenantConstant;
import org.springblade.core.launch.props.BladeProperties;
import org.springblade.core.oauth2.exception.ExceptionCode;
import org.springblade.core.oauth2.handler.AbstractAuthorizationHandler;
import org.springblade.core.oauth2.props.OAuth2Properties;
import org.springblade.core.oauth2.provider.OAuth2Request;
import org.springblade.core.oauth2.provider.OAuth2Validation;
import org.springblade.core.oauth2.service.OAuth2User;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.*;
import org.springblade.system.cache.ParamCache;
import org.springblade.system.cache.SysCache;
import org.springblade.system.pojo.entity.Tenant;
 
import java.time.Duration;
import java.util.Date;
import java.util.List;
 
import static org.springblade.auth.constant.BladeAuthConstant.FAIL_COUNT;
import static org.springblade.auth.constant.BladeAuthConstant.FAIL_COUNT_VALUE;
 
/**
 * BladeAuthorizationHandler
 *
 * @author BladeX
 */
@Slf4j
@RequiredArgsConstructor
public class BladeAuthorizationHandler extends AbstractAuthorizationHandler {
 
    private final BladeRedis bladeRedis;
    private final BladeProperties bladeProperties;
    private final BladeTenantProperties tenantProperties;
    private final OAuth2Properties oAuth2Properties;
 
    /**
     * 自定义弱密码列表
     */
    private static final List<String> WEAK_PASSWORDS = List.of("admin", "hr", "manager", "boss");
 
    /**
     * 认证前校验
     *
     * @param request 请求信息
     * @return boolean
     */
    @Override
    public OAuth2Validation preValidation(OAuth2Request request) {
        if (request.isPassword() || request.isCaptchaCode()) {
            // 生产环境弱密码校验
            if (bladeProperties.isProd() && isWeakPassword(request.getPassword())) {
                return buildValidationFailure(ExceptionCode.INVALID_USER_PASSWORD);
            }
            // 判断登录是否锁定
            OAuth2Validation failCountValidation = validateFailCount(request.getTenantId(), request.getUsername());
            if (!failCountValidation.isSuccess()) {
                return failCountValidation;
            }
        }
        return super.preValidation(request);
    }
 
    /**
     * 认证前失败回调
     *
     * @param validation 失败信息
     */
    @Override
    public void preFailure(OAuth2Request request, OAuth2Validation validation) {
        // 增加错误锁定次数
        addFailCount(request.getTenantId(), request.getUsername());
 
        log.error("用户:{},认证失败,失败原因:{}", request.getUsername(), validation.getMessage());
    }
 
    /**
     * 认证校验
     *
     * @param user    用户信息
     * @param request 请求信息
     * @return boolean
     */
    @Override
    public OAuth2Validation authValidation(OAuth2User user, OAuth2Request request) {
        // 密码模式、刷新token模式、验证码模式需要校验租户状态
        if (request.isPassword() || request.isRefreshToken() || request.isCaptchaCode()) {
            // 租户校验
            OAuth2Validation tenantValidation = validateTenant(user.getTenantId());
            if (!tenantValidation.isSuccess()) {
                return tenantValidation;
            }
            // 判断登录是否锁定
            OAuth2Validation failCountValidation = validateFailCount(user.getTenantId(), user.getAccount());
            if (!failCountValidation.isSuccess()) {
                return failCountValidation;
            }
        }
        return super.authValidation(user, request);
    }
 
    /**
     * 认证成功回调
     *
     * @param user 用户信息
     */
    @Override
    public void authSuccessful(OAuth2User user, OAuth2Request request) {
        // 清空错误锁定次数
        delFailCount(user.getTenantId(), user.getAccount());
 
        log.info("用户:{},认证成功", user.getAccount());
    }
 
    /**
     * 认证失败回调
     *
     * @param user       用户信息
     * @param validation 失败信息
     */
    @Override
    public void authFailure(OAuth2User user, OAuth2Request request, OAuth2Validation validation) {
        // 自定义认证失败回调
    }
 
    /**
     * 判断是否为弱密码
     *
     * @param rawPassword 加密密码
     * @return boolean
     */
    private boolean isWeakPassword(String rawPassword) {
        // 获取公钥
        String publicKey = oAuth2Properties.getPublicKey();
        // 获取私钥
        String privateKey = oAuth2Properties.getPrivateKey();
        // 解密密码
        String decryptPassword = SM2Util.decrypt(rawPassword, publicKey, privateKey);
        return WEAK_PASSWORDS.stream()
            .anyMatch(weakPass -> weakPass.equalsIgnoreCase(decryptPassword));
    }
 
    /**
     * 租户授权校验
     *
     * @param tenantId 租户id
     * @return OAuth2Validation
     */
    private OAuth2Validation validateTenant(String tenantId) {
        // 租户校验
        Tenant tenant = SysCache.getTenant(tenantId);
        if (tenant == null) {
            return buildValidationFailure(ExceptionCode.USER_TENANT_NOT_FOUND);
        }
        // 租户授权时间校验
        Date expireTime = tenant.getExpireTime();
        if (tenantProperties.getLicense()) {
            String licenseKey = tenant.getLicenseKey();
            String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
            Tenant license = JsonUtil.parse(decrypt, Tenant.class);
            if (license == null || !license.getId().equals(tenant.getId())) {
                return buildValidationFailure(ExceptionCode.UNAUTHORIZED_USER_TENANT);
            }
            expireTime = license.getExpireTime();
        }
        if (expireTime != null && expireTime.before(DateUtil.now())) {
            return buildValidationFailure(ExceptionCode.UNAUTHORIZED_USER_TENANT);
        }
        return new OAuth2Validation();
    }
 
    /**
     * 判断登录是否锁定
     *
     * @param tenantId 租户id
     * @param account  账号
     * @return OAuth2Validation
     */
    private OAuth2Validation validateFailCount(String tenantId, String account) {
        int cnt = getFailCount(tenantId, account);
        int failCount = Func.toInt(ParamCache.getValue(FAIL_COUNT_VALUE), FAIL_COUNT);
        if (cnt >= failCount) {
            log.error("用户:{},已锁定,请求ip:{}", account, WebUtil.getIP());
            return buildValidationFailure(ExceptionCode.USER_TOO_MANY_FAILS);
        }
        return new OAuth2Validation();
    }
 
    /**
     * 获取账号错误次数
     *
     * @param tenantId 租户id
     * @param username 账号
     * @return int
     */
    private int getFailCount(String tenantId, String username) {
        if (Func.hasEmpty(tenantId, username)) {
            return 0;
        }
        return Func.toInt(bladeRedis.get(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username)), 0);
    }
 
    /**
     * 设置账号错误次数
     *
     * @param tenantId 租户id
     * @param username 账号
     */
    private void addFailCount(String tenantId, String username) {
        if (Func.hasEmpty(tenantId, username)) {
            return;
        }
        int count = getFailCount(tenantId, username);
        bladeRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username), count + 1, Duration.ofMinutes(30));
    }
 
    /**
     * 设置账号错误次数
     *
     * @param tenantId 租户id
     * @param username 账号
     * @param count    次数
     */
    private void setFailCount(String tenantId, String username, int count) {
        bladeRedis.setEx(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username), count + 1, Duration.ofMinutes(30));
    }
 
    /**
     * 清空账号错误次数
     *
     * @param tenantId 租户id
     * @param username 账号
     */
    private void delFailCount(String tenantId, String username) {
        bladeRedis.del(CacheNames.tenantKey(tenantId, CacheNames.USER_FAIL_KEY, username));
    }
}