|
|
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);
|
}
|
|
|
}
|