[原创]JAAS 实现in Struts Web App,使用XMLPolicy文件,不改变VM安全文件(2)授权

2024-05-01 05:58

本文主要是介绍[原创]JAAS 实现in Struts Web App,使用XMLPolicy文件,不改变VM安全文件(2)授权,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本文章继续上一篇实现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.继承PrincipalPrincipalUser

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.继承PermissionPermissionCollection

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;

                        else if(token.equals(EXECUTE_ACTION))

                              mask |= EXECUTE;

                        else if(token.equals(CREATE_ACTION))

                              mask |= CREATE;

                        else if(token.equals(DELETE_ACTION))

                              mask |= DELETE;

                        else if(token.equals(DEPLOY_ACTION))

                              mask |= DEPLOY;

                        else if(token.equals(CONFIRM_ACTION))

                              mask |= CONFIRM;

                        else

                              throw new IllegalArgumentException("Unknown action: " + token);

                  }

            }

      }

      /**

       * Gets the resource

       * @return Returns a Resource

       */

      public Resource getResource() {

            return resource;

      }

 

 

 

 

      /**

       * Gets the subject

       * @return Returns a Subject

       */

      public Subject getSubject() {

            return subject;

      }    

 

 

 

 

      /**

       * @see Permission#newPermissionCollection()

       */

      public PermissionCollection newPermissionCollection() {

            return new ResourcePermissionCollection();

      }

 

 

 

 

      /**

       * @see Permission#toString()

       */

      public String toString() {

            return getName() + ":" + getActions();

      }

 

 

}

 

 

public class ResourcePermissionCollection extends PermissionCollection {

     

      private Hashtable permissions;

     

      public ResourcePermissionCollection() {

            permissions = new Hashtable();

      }

 

 

      /**

       * @see PermissionCollection#elements()

       */

      public Enumeration elements() {

            //System.out.println("DefaultResourceActionPermissionCollection.elements()");

            Hashtable list = new Hashtable();

            Enumeration enum = permissions.elements();

            while(enum.hasMoreElements()) {

                  Hashtable table = (Hashtable) enum.nextElement();

                  list.putAll(table);

            }

            return list.elements();

      }

 

 

      /**

       * @see PermissionCollection#implies(Permission)

       */

      public boolean implies(Permission permission) {

            //System.out.println("DefaultResourceActionPermissionCollection.implies()");

                       

            if( !(permission instanceof ResourcePermission) )

                  throw new IllegalArgumentException("Wrong Permission type");

                 

            ResourcePermission rcsPermission = (ResourcePermission) permission;

            Hashtable aggregate = (Hashtable) permissions.get(rcsPermission.getName());

            if(aggregate == null)

                  return false;

 

 

            Enumeration enum = aggregate.elements();

            while(enum.hasMoreElements()) {

                  ResourcePermission p = (ResourcePermission) enum.nextElement();

                  if(p.implies(permission))

                        return true;

            }

           

            return false;

      }

 

 

      /**

       * @see PermissionCollection#add(Permission)

       */

      public void add(Permission permission) {

            if(isReadOnly())

                  throw new IllegalArgumentException("Read only collection");

           

            if( !(permission instanceof ResourcePermission) )

                  throw new IllegalArgumentException("Wrong Permission type");

                 

            // Same permission names may have different relationships.

            // Therefore permissions are aggregated by relationship.

            ResourcePermission rcsPermission = (ResourcePermission) permission;

 

 

            Hashtable aggregate = (Hashtable) permissions.get(rcsPermission.getName());

 

 

                  aggregate = new Hashtable();             

           

            aggregate.put("none", rcsPermission);                      

            permissions.put(rcsPermission.getName(), aggregate);       

      }

 

 

}

8.实现授权Action

package com.nova.colimas.security.actions;

 

 

import java.security.PrivilegedAction;

import com.nova.colimas.data.sql.*;

 

 

import com.nova.colimas.data.sql.SQLTBI;

 

 

public class DBTURMAction implements PrivilegedAction {

 

 

      public Object run() {

            //验证授权

            SQLTURM sqltbi=new SQLTURM();

            sqltbi.update(null);

            return null;

      }

 

 

}

9.授权验证SQLTURM

/*

 * Created on 2005/07/01

 *

 * TODO To change the template for this generated file go to

 * Window - Preferences - Java - Code Style - Code Templates

 */

package com.nova.colimas.security.auth;

/**

 * This interface is used by implementing classes that

 * want to provide class instance authorization.

 *

 */

public interface Resource {

     

}

 

 

public class SQLTURM implements Resource{

 

 

      /* (non-Javadoc)

       * @see com.nova.colimas.data.sql.DAOAction#update(java.lang.Object)

       */

      public boolean update(Object bean) {

//验证00001角色是否有权限对SQLTURM执行write操作。

      Permission permission = new ResourcePermission("com.nova.colimas.data.sql.SQLTURM", "write", this,Subject.getSubject(java.security.AccessController.getContext()));   

            AccessController.checkPermission(permission);

      //有权限执行下面语句。无权限则抛出异常。

            return true;

      }

}

10. 实现com.nova.colimas.security.auth.AccessController类获得XMLPolicyFile实例。

package com.nova.colimas.security.auth;

 

 

import java.security.AccessControlException;

import java.security.*;

 

 

public class AccessController {

      public static void checkPermission(Permission permission)

      throws AccessControlException{

            ResourcePermission perm=(ResourcePermission)permission;

            String policy_class = null;

            XMLPolicyFile policy=null;

            policy_class = (String)java.security.AccessController.doPrivileged(

                        new PrivilegedAction() {

                              public Object run() {

                                    return Security.getProperty("policy.provider");

                              }

                        });

            try {

                  policy = ( XMLPolicyFile)

                  Class.forName(policy_class).newInstance();

                  Class permclass=Class.forName(perm.getName());

                  ResourcePermissionCollection rpc=(ResourcePermissionCollection)policy.getPermissions(perm.getSubject(),permclass.getProtectionDomain().getCodeSource());

                  if(rpc.implies(perm)) return;

            } catch (Exception e) {

                  e.printStackTrace();

            }

            throw new AccessControlException("Access Deny");

      }

}

 

 

11.实现com.nova.colimas.web.action.LoginAction

public class LoginAction extends Action {

     

      LoginContext loginContext=null;

      LoginForm loginForm=null;

      public ActionForward execute(ActionMapping mapping,

                   ActionForm form,

                   HttpServletRequest request,

                   HttpServletResponse response)

      throws Exception{

           

            /**

             * 1 get Login form Bean

             * 2 get the value

             * 3 call JAAS Login Module

             */

            try {      

                  loginForm=(LoginForm)form;

                  loginContext=new LoginContext(JAASConstants.AUTH_SECURITY_MODULENAME, new LoginCallbackHandler(loginForm.getUserID(),loginForm.getPassword()));

                 

            }catch(SecurityException e){

                  e.printStackTrace();

            } catch (LoginException e) {

                  e.printStackTrace();

                  //System.exit(-1);

            }

            // Authenticate the user

            try {

                  loginContext.login

                  //验证是否有权限运行DBTURMAction

                  Subject.doAs(loginContext.getSubject(),new DBTURMAction() );                             

                  System.out.println("Successfully!/n");   

                 

            } catch (Exception e) {

                  System.out.println("Unexpected Exception - unable to continue");

                  e.printStackTrace();

                  //System.exit(-1);

                  return mapping.findForward("failure");

            }          

      return mapping.findForward("success");

      }

}

这篇关于[原创]JAAS 实现in Struts Web App,使用XMLPolicy文件,不改变VM安全文件(2)授权的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/950865

相关文章

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

Go语言数据库编程GORM 的基本使用详解

《Go语言数据库编程GORM的基本使用详解》GORM是Go语言流行的ORM框架,封装database/sql,支持自动迁移、关联、事务等,提供CRUD、条件查询、钩子函数、日志等功能,简化数据库操作... 目录一、安装与初始化1. 安装 GORM 及数据库驱动2. 建立数据库连接二、定义模型结构体三、自动迁