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