com.soento.security.util.OauthUtil Maven / Gradle / Ivy
The newest version!
package com.soento.security.util;
import com.soento.core.base.lang.UserInfo;
import com.soento.core.base.util.JsonUtil;
import com.soento.security.lang.OauthUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import java.util.Map;
/**
* @author soento
*/
public class OauthUtil {
private final static Logger log = LoggerFactory.getLogger(OauthUtil.class);
public static UserInfo getUser(Authentication authentication) {
if (authentication == null) {
return null;
}
try {
if (authentication.getPrincipal() instanceof OauthUser) {
UserInfo userInfo = new UserInfo();
BeanUtils.copyProperties(authentication.getPrincipal(), userInfo);
return userInfo;
} else if (authentication instanceof OAuth2Authentication) {
Object principal = ((Map) (((OAuth2Authentication) authentication).getUserAuthentication().getDetails())).get("principal");
return JsonUtil.toObject(JsonUtil.toJson(principal), UserInfo.class);
} else {
log.info("Authentication not mapping");
return null;
}
} catch (Exception e) {
log.info(e.getMessage(), e);
return null;
}
}
public static UserInfo getUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return getUser(authentication);
}
}