选择显示字体大小

jaas 实现in struts web app,使用xmlpolicy文件,不改变vm安全文件(2)

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:  &quot;/policy/grant&#91;@codebase=\&quot;sample_actions.jar\&quot;&#93;/principal&#91;@classname=\&quot;com.fonseca.security.sampleprincipal\&quot;&#93;&#91;@name=\&quot;testuser\&quot;&#93;/permission&quot;
                            stringbuffer xpath = new stringbuffer();

                            xpath.append(&quot;/policy/grant/principal&#91;@classname=\&quot;&quot;);                
                            xpath.append(principal.getclass().getname());
                            xpath.append(&quot;\&quot;&#93;&#91;@name=\&quot;&quot;);
                            xpath.append(principal.getname());
                             xpath.append(&quot;\&quot;&#93;/permission&quot;);
                             
                             //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(&quot;classname&quot;);
                attr attrname = (attr) map.getnameditem(&quot;name&quot;);                                        
                attr attractions = (attr) map.getnameditem(&quot;actions&quot;);                                        
                attr attrrelationship = (attr) map.getnameditem(&quot;relationship&quot;);                                        
                
                if(attrclassname == null)
                        throw new runtimeexception();
                
                class&#91;&#93; types = null;
                object&#91;&#93; 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&#91;2&#93;;
                                        args = new object&#91;2&#93;;
                                } else {
                                        types = new class&#91;3&#93;;
                                        args = new object&#91;3&#93;;
                                        string relationship = attrrelationship.getvalue();
                                        types&#91;2&#93; = relationship.getclass();
                                        args&#91;2&#93; = relationship;
                                }
                        
                                types&#91;1&#93; = actions.getclass();                        
                                args&#91;1&#93; = actions;
                        
                        } else {
                                types = new class&#91;1&#93;;
                                args = new object&#91;1&#93;;                
                        }
                                
                        types&#91;0&#93; = name.getclass();
                        args&#91;0&#93; = 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&#91;&#93; certs = null;
                url location;

                if(node.getnodename().equalsignorecase(&quot;grant&quot;)) {
                        namednodemap map = node.getattributes();

                        attr attrcodebase = (attr) map.getnameditem(&quot;codebase&quot;);
                        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(&quot;name cannot be null&quot;);
                //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 = &quot;owner&quot;;
        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    = &quot;read&quot;;
        static final public string write_action   = &quot;write&quot;;
        static final public string execute_action = &quot;execute&quot;;
        static final public string create_action  = &quot;create&quot;;
        static final public string delete_action  = &quot;delete&quot;;
        static final public string deploy_action  = &quot;deploy&quot;;
        static final public string confirm_action = &quot;confirm&quot;;
        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(&quot;, &quot;);
                        buf.append(write_action);
                }
                if( (mask & execute) == execute ) {
                        if(buf.length() > 0)
                                buf.append(&quot;, &quot;);
                        buf.append(execute_action);
                }
                if( (mask & create) == create ) {
                        if(buf.length() > 0)
                                buf.append(&quot;, &quot;);
                        buf.append(create_action);
                }
                if( (mask & delete) == delete ) {
                        if(buf.length() > 0)
                                buf.append(&quot;, &quot;);
                        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, &quot;,\t &quot;);                
                        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(&quot;unknown action: &quot; + 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() + &quot;:&quot; + getactions();
        }

}

public class resourcepermissioncollection extends permissioncollection {
        
        private hashtable permissions;
        
        public resourcepermissioncollection() {
                permissions = new hashtable();
        }

        /**
         * @see permissioncollection#elements()
         */
        public enumeration elements() {
                //system.out.println(&quot;defaultresourceactionpermissioncollection.elements()&quot;);
                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(&quot;defaultresourceactionpermissioncollection.implies()&quot;);
                                
                if( !(permission instanceof resourcepermission) )
                        throw new illegalargumentexception(&quot;wrong permission type&quot;);
                        
                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(&quot;read only collection&quot;);
                
                if( !(permission instanceof resourcepermission) )
                        throw new illegalargumentexception(&quot;wrong permission type&quot;);
                        
                // 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(&quot;none&quot;, 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(&quot;com.nova.colimas.data.sql.sqlturm&quot;, &quot;write&quot;, 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(&quot;policy.provider&quot;);
                                        }
                                });
                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(&quot;access deny&quot;);
        }
}


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();//先运行colimasloginmodule的initialize(subject, callbackhandler, map, map)方法,然后运行colimasloginmodule的login()
                        system.out.println(&quot;\ncreating a new userprofile...&quot;);                //验证是否有权限运行dbturmaction
                        subject.doas(logincontext.getsubject(),new dbturmaction() );                                        
                        system.out.println(&quot;successfully!\n&quot;);        
                        
                } catch (exception e) {
                        system.out.println(&quot;unexpected exception - unable to continue&quot;);
                        e.printstacktrace();
                        //system.exit(-1);
                        return mapping.findforward(&quot;failure&quot;);
                }                
      return mapping.findforward(&quot;success&quot;);
        }
}




 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons