本文章继续上一篇实现WebApp的授权
5. 实现XMLPolicyFile类。
public class XMLPolicyFile extends Policy implements JAASConstants {
private Document doc = null;
//private CodeSource noCertCodeSource=null;
/*
* constructor
* refresh()
*/
public XMLPolicyFile(){
refresh();
}
public PermissionCollection getPermissions(CodeSource arg0) {
// TODO Auto-generated method stub
return null;
}
/*
* Creates a DOM tree document from the default XML file or
* from the file specified by the system property,
* <code>com.ibm.resource.security.auth.policy</code>. This
* DOM tree document is then used by the
* <code>getPermissions()</code> in searching for permissions.
*
* @see javax.security.auth.Policy#refresh()
*/
public void refresh() {
FileInputStream fis = null;
try {
// Set up a DOM tree to query
fis = new FileInputStream(AUTH_SECURITY_POLICYXMLFILE);
InputSource in = new InputSource(fis);
DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
dfactory.setNamespaceAware(true);
doc = dfactory.newDocumentBuilder().parse(in);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
} finally {
if(fis != null) {
try { fis.close(); } catch (IOException e) {}
}
}
}
public PermissionCollection getPermissions(Subject subject,CodeSource codeSource) {
ResourcePermissionCollection collection = new ResourcePermissionCollection();
try {
// Iterate through all of the subjects principals
Iterator principalIterator = subject.getPrincipals().iterator();
while(principalIterator.hasNext()){
Principal principal = (Principal)principalIterator.next();
// Set up the xpath string to retrieve all the relevant permissions
// Sample xpath string: "/policy/grant[@codebase=\"sample_actions.jar\"]/principal[@classname=\"com.fonseca.security.SamplePrincipal\"][@name=\"testUser\"]/permission"
StringBuffer xpath = new StringBuffer();
xpath.append("/policy/grant/principal[@classname=\"");
xpath.append(principal.getClass().getName());
xpath.append("\"][@name=\"");
xpath.append(principal.getName());
xpath.append("\"]/permission");
//System.out.println(xpath.toString());
NodeIterator nodeIter = XPathAPI.selectNodeIterator(doc, xpath.toString());
Node node = null;
while( (node = nodeIter.nextNode()) != null ) {
//here
CodeSource codebase=getCodebase(node.getParentNode().getParentNode());
if (codebase!=null || codebase.implies(codeSource)){
Permission permission = getPermission(node);
collection.add(permission);
}
}
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
if(collection != null)
return collection;
else {
// If the permission is not found here then delegate it
// to the standard java Policy class instance.
Policy policy = Policy.getPolicy();
return policy.getPermissions(codeSource);
}
}
/**
* Returns a Permission instance defined by the provided
* permission Node attributes.
*/
private Permission getPermission(Node node) throws Exception {
NamedNodeMap map = node.getAttributes();
Attr attrClassname = (Attr) map.getNamedItem("classname");
Attr attrName = (Attr) map.getNamedItem("name");
Attr attrActions = (Attr) map.getNamedItem("actions");
Attr attrRelationship = (Attr) map.getNamedItem("relationship");
if(attrClassname == null)
throw new RuntimeException();
Class[] types = null;
Object[] args = null;
// Check if the name is specified
// if no name is specified then because
// the types and the args variables above
// are null the default constructor is used.
if(attrName != null) {
String name = attrName.getValue();
// Check if actions are specified
// then setup the array sizes accordingly
if(attrActions != null) {
String actions = attrActions.getValue();
// Check if a relationship is specified
// then setup the array sizes accordingly
if(attrRelationship == null) {
types = new Class[2];
args = new Object[2];
} else {
types = new Class[3];
args = new Object[3];
String relationship = attrRelationship.getValue();
types[2] = relationship.getClass();
args[2] = relationship;
}
types[1] = actions.getClass();
args[1] = actions;
} else {
types = new Class[1];
args = new Object[1];
}
types[0] = name.getClass();
args[0] = name;
}
String classname = attrClassname.getValue();
Class permissionClass = Class.forName(classname);
Constructor constructor = permissionClass.getConstructor(types);
return (Permission) constructor.newInstance(args);
}
/**
* Returns a CodeSource object defined by the provided
* grant Node attributes.
*/
private java.security.CodeSource getCodebase(Node node) throws Exception {
Certificate[] certs = null;
URL location;
if(node.getNodeName().equalsIgnoreCase("grant")) {
NamedNodeMap map = node.getAttributes();
Attr attrCodebase = (Attr) map.getNamedItem("codebase");
if(attrCodebase != null) {
String codebaseValue = attrCodebase.getValue();
location = new URL(codebaseValue);
return new CodeSource(location,certs);
}
}
return null;
}
}
6.继承Principal类PrincipalUser
public class PrincipalUser implements Principal {
private String name;
/**
*
* @param name the name for this principal.
*
* @exception InvalidParameterException if the <code>name</code>
* is <code>null</code>.
*/
public PrincipalUser(String name) {
if (name == null)
throw new InvalidParameterException("name cannot be null");
//search role of this name.
this.name = name;
}
/**
* Returns the name for this <code>PrincipalUser</code>.
*
* @return the name for this <code>PrincipalUser</code>
*/
public String getName() {
return name;
}
/**
*
*/
public int hashCode() {
return name.hashCode();
}
}
7.继承Permission和PermissionCollection类
public class ResourcePermission extends Permission {
static final public String OWNER_RELATIONSHIP = "OWNER";
static private int READ = 0x01;
static private int WRITE = 0x02;
static private int EXECUTE = 0x04;
static private int CREATE = 0x08;
static private int DELETE = 0x10;
static private int DEPLOY = 0x16;
static private int CONFIRM = 0x24;
static final public String READ_ACTION = "read";
static final public String WRITE_ACTION = "write";
static final public String EXECUTE_ACTION = "execute";
static final public String CREATE_ACTION = "create";
static final public String DELETE_ACTION = "delete";
static final public String DEPLOY_ACTION = "deploy";
static final public String CONFIRM_ACTION = "confirm";
protected int mask;
protected Resource resource;
protected Subject subject;
/**
* Constructor for ResourcePermission
*/
public ResourcePermission(String name, String actions, Resource resource, Subject subject) {
super(name);
this.resource = resource;
this.subject = subject;
parseActions(actions);
}
/**
* @see Permission#getActions()
*/
public String getActions() {
StringBuffer buf = new StringBuffer();
if( (mask & READ) == READ )
buf.append(READ_ACTION);
if( (mask & WRITE) == WRITE ) {
if(buf.length() > 0)
buf.append(", ");
buf.append(WRITE_ACTION);
}
if( (mask & EXECUTE) == EXECUTE ) {
if(buf.length() > 0)
buf.append(", ");
buf.append(EXECUTE_ACTION);
}
if( (mask & CREATE) == CREATE ) {
if(buf.length() > 0)
buf.append(", ");
buf.append(CREATE_ACTION);
}
if( (mask & DELETE) == DELETE ) {
if(buf.length() > 0)
buf.append(", ");
buf.append(DELETE_ACTION);
}
return buf.toString();
}
/**
* @see Permission#hashCode()
*/
public int hashCode() {
StringBuffer value = new StringBuffer(getName());
return value.toString().hashCode() ^ mask;
}
/**
* @see Permission#equals(Object)
*/
public boolean equals(Object object) {
if( !(object instanceof ResourcePermission) )
return false;
ResourcePermission p = (ResourcePermission) object;
return ( (p.getName().equals(getName())) && (p.mask == mask) );
}
/**
* @see Permission#implies(Permission)
*/
public boolean implies(Permission permission) {
// The permission must be an instance
// of the DefaultResourceActionPermission.
if( !(permission instanceof ResourcePermission) )
return false;
// The resource name must be the same.
if( !(permission.getName().equals(getName())) )
return false;
return true;
}
/**
* Parses the actions string. Actions are separated
* by commas or white space.
*/
private void parseActions(String actions) {
mask = 0;
if(actions != null) {
StringTokenizer tokenizer = new StringTokenizer(actions, ",\t ");
while(tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if(token.equals(READ_ACTION))
mask |= READ;
else if(token.equals(WRITE_ACTION))
mask |= WRITE;
<
分享到:
相关推荐
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种标准框架来实现用户身份验证和授权。在Web应用程序中,JAAS被用来控制对资源的访问,确保只有经过验证的用户...
2. JAAS读取配置文件,确定要使用的登录模块。 3. 每个登录模块依次执行,验证用户凭证。 4. 如果所有登录模块都成功,主体被创建并填充认证信息。 5. 应用程序可以使用主体的信息进行授权决策。 ### 四、JAAS与...
文章提到,在 Borland 应用服务器的基础上,使用 JAAS 与 J2EE Web 容器的内置安全机制,并结合 Oracle 数据库的用户验证功能,实现了 Web 应用中对用户的验证和授权。这种方法的一个关键优势在于,它可以将用户能...
通过以上步骤,我们成功地使用 JAAS 在 Web 应用中实现了基本的页面验证与授权功能。这种实现方式不仅增强了系统的安全性,还简化了开发者的工作流程,使得用户认证和授权管理变得更加灵活和高效。
- 分析JAAS源码可以帮助理解其内部工作流程,有助于优化和调试自定义安全实现。 6. **工具支持** - 开发和调试JAAS配置可以使用各种工具,如Eclipse IDE的插件,这些工具可以帮助简化配置过程并进行测试。 7. **...
综上所述,《JAAS in Action》是一本深入了解Java安全体系的宝贵资源,对于希望在Java环境中构建安全系统的开发者来说,是不可或缺的学习材料。通过阅读这些章节,读者不仅可以理解JAAS的基本工作原理,还能学习到...
现在,让我们来看看如何使用纯 Java 文件实现一个简单的 JAAS 示例: 1. **创建登录模块(LoginModule)**:首先,你需要创建一个实现了 `javax.security.auth.spi.LoginModule` 接口的类。这个接口定义了几个关键...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全认证和授权的核心组件。它为开发者提供了一种标准的方式来实现用户身份验证和访问控制,从而确保应用程序的安全性。"Jaas in Action"这...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种框架,用于在Java应用程序中实现认证(Authentication)和授权(Authorization)。`jaas.jar` 文件是这个...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种框架,使得应用程序能够实现用户身份验证和权限管理。在这个教程中,我们将深入探讨JAAS的核心概念、工作...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现用户认证和权限授权的一个核心组件。它为开发者提供了一种灵活的方式来实现安全控制,确保只有经过验证和授权的用户能够访问敏感资源或...
2. **定义策略**:`demo.policy` 文件是Java安全策略文件,它指定了哪些权限被授予哪个主体(principal)。策略文件使用一种特定的语法,允许开发者精确地控制哪些代码段或用户可以执行特定操作。例如,你可以指定...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现安全认证和授权的核心框架。它为开发者提供了一种标准化的方法来处理用户身份验证和权限控制,使得应用程序能够根据用户的身份和角色来...
Java Authentication and Authorization Service (JAAS) 是Java平台提供的一种安全框架,用于实现用户身份验证和权限管理。这个框架使得开发者可以轻松地在Java应用程序中集成安全性,而不必深入理解底层的复杂安全...
在Mac版Tomcat中配置JAAS,可以确保只有经过验证的用户才能访问Web应用程序,从而增强系统的安全性。 首先,让我们了解一下JAAS的基本概念。JAAS定义了一种框架,允许开发人员创建和集成各种认证模块,这些模块可以...
总的来说,"Java JAAS安全认证 demo"是一个实用的学习资源,它展示了Java平台内置的安全机制,这对于构建安全的Web应用或企业级服务至关重要。开发者可以通过研究这个示例,掌握在实际项目中实施安全认证的最佳实践...
JAAS提供了一种标准的方式来实现这一目标,允许开发者在不深入了解底层安全机制的情况下,构建安全的应用程序。 **JAAS 登录验证机制** JAAS的核心概念是登录模块(LoginModule),它是处理用户身份验证逻辑的组件...
3. **拦截器实现授权**:Struts的Interceptor机制允许我们在Action执行前后插入自定义逻辑。我们可以创建一个权限检查拦截器,该拦截器在每个Action执行前检查Session中的用户角色是否有执行该Action的权限。如果...