一、前言
关于apache的hadoop-gateway-spi源码包定义org.apache.hadoop.gateway.security.SubjectUtils主题工具类,通过获取当前访问getCurrentSubject得到javax.security.auth.Subject主体会话对象、获取当前java.security.Principal姓名等信息。
二、代码示例
1.SubjectUtils类
package org.apache.hadoop.gateway.security;@b@@b@import java.security.AccessController;@b@import java.security.Principal;@b@import java.util.Iterator;@b@import java.util.Set;@b@import javax.security.auth.Subject;@b@@b@public class SubjectUtils@b@{@b@ public static Subject getCurrentSubject()@b@ {@b@ return Subject.getSubject(AccessController.getContext());@b@ }@b@@b@ public static String getPrimaryPrincipalName(Subject subject) {@b@ String name = null;@b@@b@ Set primaryPrincipals = subject.getPrincipals(PrimaryPrincipal.class);@b@ if (primaryPrincipals.size() > 0) {@b@ return ((PrimaryPrincipal)primaryPrincipals.toArray()[0]).getName();@b@ }@b@@b@ Set principals = subject.getPrincipals();@b@ Iterator i$ = principals.iterator(); if (i$.hasNext()) { Principal p = (Principal)i$.next();@b@ name = p.getName();@b@ }@b@@b@ return name;@b@ }@b@@b@ public static boolean isImpersonating(Subject subject) {@b@ boolean impersonating = false;@b@@b@ impersonating = subject.getPrincipals(ImpersonatedPrincipal.class).size() > 0;@b@@b@ return impersonating;@b@ }@b@@b@ public static String getImpersonatedPrincipalName(Subject subject) {@b@ String name = null;@b@@b@ Set impPrincipals = subject.getPrincipals(ImpersonatedPrincipal.class);@b@ if (impPrincipals.size() > 0) {@b@ return ((Principal)impPrincipals.toArray()[0]).getName();@b@ }@b@@b@ return name;@b@ }@b@@b@ public static String getEffectivePrincipalName(Subject subject) {@b@ String name = null;@b@@b@ name = getImpersonatedPrincipalName(subject);@b@ if (name == null) {@b@ name = getPrimaryPrincipalName(subject);@b@ }@b@@b@ return name;@b@ }@b@}
2.PrimaryPrincipal类
package org.apache.hadoop.gateway.security;@b@@b@import java.security.Principal;@b@@b@public class PrimaryPrincipal@b@ implements Principal@b@{@b@ private String name = null;@b@@b@ public PrimaryPrincipal(String name)@b@ {@b@ this.name = name;@b@ }@b@@b@ public String getName() {@b@ return this.name;@b@ }@b@}