SecurityContext

/*
* Copyright Huawei Symantec Technologies Co.,Ltd. 2008-2009. All rights reserved.
*
*
*/

package com.huaweisymantec.core.service;

import java.util.Collection;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.huaweisymantec.omm.domain.system.RoleEnum;

/**
* Security资源获取通用类
*
*/
public final class SecurityContext {

private SecurityContext() {

}

/**
* 登陆成功后,得到当前用户的用户名
*
* @return String
*/
public static String getPrincipal() {
String username = null;
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if(authentication==null){
return null;
}
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (obj instanceof UserDetails) {
username = ((UserDetails) obj).getUsername();
} else {
username = obj.toString();
}
return username;
}

/**
* 登陆成功后,判断当前用户是否为超级管理员
*
* @return boolean
*/
public static boolean isAdmin() {
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (obj instanceof UserDetails) {
Collection authorities = ((UserDetails) obj).getAuthorities();
for (GrantedAuthority grantedAuthority : authorities) {
if (grantedAuthority.getAuthority().equals(RoleEnum.ROLE_ADMIN.name())) {
return true;
}
}
}
return false;
}
}

你可能感兴趣的:(ssss)