86183
2022-09-09 0d999e33085c0a25c5525242748f6aa62a401159
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
 
 
package cn.mb.cloud.auth.security.util;
 
 
import cn.mb.cloud.auth.security.component.MbCloudAuthUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
 
/**
 * 安全工具类
 *
 * @author L.cm
 */
@UtilityClass
public class  SecurityUtils {
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
 
    /**
     * 获取用户
     *
     * @param authentication
     * @return MbCloudAuthUser
     * <p>
     * 获取当前用户的全部信息  true
     * 获取当前用户的用户名  false
     */
    public MbCloudAuthUser getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof MbCloudAuthUser) {
            return (MbCloudAuthUser) principal;
        }
        return null;
    }
 
    /**
     * 获取当前用名
     *
     * @return String
     */
    public String getUsername() {
        Object principal = getAuthentication().getPrincipal();
        if (principal instanceof String) {
            return principal.toString();
        }
        return null;
    }
 
 
    public String getClientId() {
        Authentication authentication = getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }
 
    /**
     * 获取用户
     */
    public MbCloudAuthUser getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }
 
 
}