陶杰
2024-08-22 ee9032d9baf5f33e376d2d2699136e0a7b26bec7
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
package com.mzl.flower.config.security;
 
import com.mzl.flower.dto.security.UserDTO;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
 
@UtilityClass
public class SecurityUtils {
 
    /**
     * 获取Authentication
     */
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }
 
    /**
     * 获取用户
     */
    public UserDTO getUser(Authentication authentication) {
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDTO) {
            return (UserDTO) principal;
        }
        return null;
    }
 
    /**
     * 获取用户
     */
    public UserDTO getUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return getUser(authentication);
    }
 
 
    public String getUserName() {
        UserDTO authUser = getUser();
        if (authUser != null) {
            return authUser.getName();
        }
        return null;
    }
 
    public String getUserType() {
        UserDTO authUser = getUser();
        if (authUser != null) {
            return authUser.getUserType();
        }
        return null;
    }
 
    public String getUserId() {
        UserDTO authUser = getUser();
        if (authUser != null) {
            return authUser.getId();
        }
        return null;
    }
 
    public String getClientId() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        try {
            OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;
            OAuth2Request authorizationRequest = oAuth2Authentication.getOAuth2Request();
            if(authorizationRequest == null){
                return null;
            }
            return authorizationRequest.getClientId();
        } catch (Exception e) {
            return null;
        }
    }
}