[原创]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

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

使用SecondaryNameNode恢复NameNode的数据

1)需求: NameNode进程挂了并且存储的数据也丢失了,如何恢复NameNode 此种方式恢复的数据可能存在小部分数据的丢失。 2)故障模拟 (1)kill -9 NameNode进程 [lytfly@hadoop102 current]$ kill -9 19886 (2)删除NameNode存储的数据(/opt/module/hadoop-3.1.4/data/tmp/dfs/na

Hadoop数据压缩使用介绍

一、压缩原则 (1)运算密集型的Job,少用压缩 (2)IO密集型的Job,多用压缩 二、压缩算法比较 三、压缩位置选择 四、压缩参数配置 1)为了支持多种压缩/解压缩算法,Hadoop引入了编码/解码器 2)要在Hadoop中启用压缩,可以配置如下参数

Makefile简明使用教程

文章目录 规则makefile文件的基本语法:加在命令前的特殊符号:.PHONY伪目标: Makefilev1 直观写法v2 加上中间过程v3 伪目标v4 变量 make 选项-f-n-C Make 是一种流行的构建工具,常用于将源代码转换成可执行文件或者其他形式的输出文件(如库文件、文档等)。Make 可以自动化地执行编译、链接等一系列操作。 规则 makefile文件

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

使用opencv优化图片(画面变清晰)

文章目录 需求影响照片清晰度的因素 实现降噪测试代码 锐化空间锐化Unsharp Masking频率域锐化对比测试 对比度增强常用算法对比测试 需求 对图像进行优化,使其看起来更清晰,同时保持尺寸不变,通常涉及到图像处理技术如锐化、降噪、对比度增强等 影响照片清晰度的因素 影响照片清晰度的因素有很多,主要可以从以下几个方面来分析 1. 拍摄设备 相机传感器:相机传

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo