SecurityUtil--自定義權限工具類

package cn.webyun.asksea.core.util;

import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import cn.webyun.asksea.core.security.CustomUserDetails;
import org.springframework.util.CollectionUtils;

/**
 * @Project: asksea-web
 * @Title: SecurityUtil
 * @Description: 
 * @Author: fujm
 * @Date: 2018年9月21日 下午2:57:58
 * @Company: webyun
 * @Copyright: Copyright (c) 2017-2018 Webyun. All Rights Reserved.
 */
public class SecurityUtil {

   public final static String LOGOUT_USER = "anonymousUser";


   /**
    * 獲取當前登錄用戶信息
    * @author fujm
    * @date 2019/1/25 9:36
    * @return
   **/
   public static CustomUserDetails getCurrentUserProfile() {
      Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      if(principal == null) {
         return null;
      }
      if((principal instanceof String) && (LOGOUT_USER.equals(principal))) {
         return null;
      }
      if(principal instanceof CustomUserDetails) {
         return (CustomUserDetails) principal;
      }
      return null;
   }


   /**
    * 驗證當前登錄用戶是否擁有指定權限
    * @author fujm
    * @date 2019/1/25 9:36
    * @param auth 權限字符串
    * @return
   **/
   public static boolean hasAuthority(String auth) {
      CustomUserDetails currentUserProfile = SecurityUtil.getCurrentUserProfile();
      if(currentUserProfile == null) {
         return false;
      }
      if( ! CollectionUtils.isEmpty(currentUserProfile.getAuthorities())
                  && currentUserProfile.getAuthorities().contains(new SimpleGrantedAuthority(auth)) ) {
         return true;
      }
      return false;
   }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章