选择显示字体大小

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

jaas参考资料中流行的文章是扩展jaas实现类实例级授权

但它是基于jdk1.3,与目前的jdk1.4,jdk1.5不兼容,例如其中的配置如下:

the following assumes you are using jdk 1.3 and the files were extracted to
the d:\jaasexample directory. you will save some work by extracting the files
to this directory otherwise you will have to modify the policy and the resourcesecurity.xml
policy files with the correct path names.

1) copy the jaas.jar and the jaasmod.jar to your jdk jre\lib\ext directory
(i.e. d:\jdk1.3\jre\lib\ext).

2) add the following to the end of the java.security file located in jdk's
jre\lib\security directory (i.e. d:\jdk1.3\jre\lib\security):
auth.policy.provider=com.ibm.resource.security.auth.xmlpolicyfile

3) execute the run.bat file.

1.4以后为policy.provider=policyfile。而且需要修改java.security文件
我经过2天的呕血奋战实现了不改变java vm环境和web server环境,在struts下实现jaas。
步骤如下:

1.      welcome.jsp, index.jsp, struts-config.xml

<%@ taglib uri=&quot;/tags/struts-logic&quot; prefix=&quot;logic&quot; %>
<logic:redirect forward=&quot;index&quot;/>
<%-- welcome.jsp
redirect default requests to welcome global actionforward.
by using a redirect, the user-agent will change address to match the path of our welcome actionforward.
--%>


index.jsp

<%@ page contenttype=&quot;text/html; charset=utf-8&quot;%>
<%@ taglib uri=&quot;/tags/struts-bean&quot; prefix=&quot;bean&quot;%>
<%@ taglib uri=&quot;/tags/struts-html&quot; prefix=&quot;html&quot;%>
<%@ taglib uri=&quot;/tags/struts-logic&quot; prefix=&quot;logic&quot;%>

<html:html>
<title>logon</title>
<body>
<html:form action=&quot;/loginaction.do&quot;>
        <p>user id: <input type=&quot;text&quot; name=&quot;userid&quot; value=&quot;tyrone&quot; /><br>
        passord: <input type=&quot;password&quot; name=&quot;password&quot; value=&quot;password&quot;/><br>
        <html:submit /></p>
</html:form>
</body>
</html:html>


struts-config.xml

<?xml version=&quot;1.0&quot; encoding=&quot;iso-8859-1&quot; ?>

<!doctype struts-config public
          &quot;-//apache software foundation//dtd struts configuration 1.2//en&quot;
          &quot;http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd&quot;>

<struts-config>
<!-- ================================================ form bean definitions -->

    <form-beans>        
          <!--2 login formbean-->    
        <form-bean
            name=&quot;loginform&quot;
            type=&quot;com.nova.colimas.web.form.loginform&quot;/>
    </form-beans>
     <global-forwards>
        <!-- default forward to &quot;welcome&quot; action -->
        <!-- demonstrates using index.jsp to forward -->
        <forward
            name=&quot;index&quot;
            path=&quot;/index.do&quot;/>
    </global-forwards>
<!-- =========================================== action mapping definitions -->
    <action-mappings>
            <!-- default &quot;welcome&quot; action -->
            <!-- forwards to welcome.jsp -->
        <action  path=&quot;/index&quot;
                type=&quot;com.nova.colimas.web.action.startupservlet&quot;>
            <forward name=&quot;success&quot; path=&quot;/pages/index.jsp&quot;/>  
        </action>
         <!-- 2 login -->
          <action    path=&quot;/loginaction&quot;
              type=&quot;com.nova.colimas.web.action.loginaction&quot;
              name=&quot;loginform&quot;
              scope=&quot;request&quot;
              input=&quot;/pages/indexcon.jsp&quot;
              validate=&quot;true&quot;>
                <forward name=&quot;success&quot; path=&quot;/pages/index.jsp&quot;/>
                <forward name=&quot;failure&quot; path=&quot;/pages/index.jsp&quot;/>
         </action>
    </action-mappings>
</struts-config>


2.      实现com.nova.colimas.web.action.startupservlet用来初始化jaas需要的系统属性

public class startupservlet extends action {

        public actionforward execute(actionmapping mapping,
                         actionform form,
                         httpservletrequest request,
                         httpservletresponse response)
        throws exception{
                // initialization of the log
                //loggerfactory.setfactory(new epricerlogfactory ());
                //log.info (this, &quot;startup of settings application&quot;);

                initjaas();
                return mapping.findforward(&quot;success&quot;);
        }
        //初始化jaas需要的系统属性
        private void initjaas(){
                //set env variable
        //用于认证jaasconstants接口内保存login.config文件地址        system.setproperty(&quot;java.security.auth.login.config&quot;,jaasconstants.auth_security_loginfile);
                }
}


public interface jaasconstants {
        string auth_security_policyxmlfile=&quot;d:\\myproject\\colimas\\clms-web\\colimas\\security-policy.xml&quot;;
        string auth_security_loginfile=&quot;d:\\myproject\\colimas\\clms-web\\colimas\\login.config&quot;;
        string auth_security_modulename=&quot;colimaslogin&quot;;
}


login.config文件内容:

colimaslogin {
   com.nova.colimas.security.auth.colimasloginmodule required debug=true;
};


3.实现colimasloginmodule登录模块
/*
* 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;

import java.util.*;
import javax.security.auth.*;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.loginmodule;
//import java.security.*;
//import org.w3c.dom.traversal.*;
import org.w3c.dom.*;
//import org.apache.xpath.*;


/**
* @author tyrone
*
* todo to change the template for this generated type comment go to
* window - preferences - java - code style - code templates
*/
public class colimasloginmodule implements loginmodule {

        private subject subject;
        private callbackhandler callbackhandler;
        private boolean debug = false;
        private boolean succeeded = false;
        private boolean commitsucceeded = false;
        private string username;
        private char&#91;&#93; password;


        /**
         * initializes the <code>loginmodule</code>.
         *
         * @param subject the <code>subject</code> to be authenticated.
         *
         * @param callbackhandler a <code>callbackhandler</code> for
         * prompting and retrieving the userid and password from the user.
         *
         * @param sharedstate shared <code>loginmodule</code> state.
         *
         * @param options options specified in the login configuration
         * file for this <code>loginmodule</code>.
         */
        public void initialize(subject subject, callbackhandler callbackhandler, map sharedstate, map options) {

                this.subject = subject;
                this.callbackhandler = callbackhandler;
                // initialize configuration options                
                debug = &quot;true&quot;.equalsignorecase((string) options.get(&quot;debug&quot;));
        }


        /**
         * prompts the user for a userid and password.
         *
         * @return true if the authentication succeeded,
         * or false if this loginmodule should be ignored
         *
         * @exception failedloginexception if the authentication fails.
         *
         * @exception loginexception if the <code>loginmodule</code>
         * is unable to authenticate.
         */
        public boolean login() throws loginexception {

                if (callbackhandler == null)
                        throw new loginexception(&quot;error: callbackhandler cannot be null&quot;);

                callback&#91;&#93; callbacks = new callback&#91;2&#93;;
                callbacks&#91;0&#93; = new namecallback(&quot;userid: &quot;);
                callbacks&#91;1&#93; = new passwordcallback(&quot;password: &quot;, false);

                try {
                        callbackhandler.handle(callbacks);
                        username = ((namecallback) callbacks&#91;0&#93;).getname();
                        char&#91;&#93; tmppassword = ((passwordcallback) callbacks&#91;1&#93;).getpassword();
                        
                        if (tmppassword == null) {
                                // treat a null password as an empty password
                                tmppassword = new char&#91;0&#93;;
                        }
                        password = new char&#91;tmppassword.length&#93;;
                        system.arraycopy(tmppassword, 0, password, 0, tmppassword.length);
                        ((passwordcallback) callbacks&#91;1&#93;).clearpassword();

                } catch (java.io.ioexception e) {
                        throw new loginexception(e.getmessage());
                } catch (unsupportedcallbackexception e) {
                        throw new loginexception(&quot;error: &quot; + e.getmessage());
                }

                if(debug) {
                        //system.out.println(&quot;colimasloginmodule: userid = &quot; + username);
                        string pwd = new string(password);
                        system.out.println(&quot;colimasloginmodule: password = &quot; + pwd);
                }

                // check the userid and password
                if (isvaliduser(username, password)) {
                        // authentication succeeded
                        if(debug)
                                system.out.println(&quot;colimasloginmodule: authentication succeeded&quot;);
                        succeeded = true;
                        return true;
                } else {
                        // authentication failed
                        if(debug)
                                system.out.println(&quot;colimasloginmodule: authentication failed&quot;);
                        succeeded = false;
                        // clear the values
                        username = null;
                        password = null;
                        throw new failedloginexception(&quot;invalid userid or password&quot;);
                }
                

        }


        /**
         * this method is called if the logincontext's overall authentication
         * succeeded (the relevant required, requisite, sufficient and
         * optional loginmodules succeeded).
         * <p>
         * if this loginmodule's own authentication attempt succeeded
         * (checked by retrieving the private state saved by the
         * <code>login</code> method), then this method associates the
         * relevant <code>principalexamples</code> with the
         * <code>subject</code> located in the <code>loginmodule</code>.
         * if this loginmodule's own authentication attempted failed, then
         * this method removes any state that was originally saved.
         *
         * @exception loginexception if the commit fails.
         *
         * @return true if this loginmodule's own login and commit attempts
         * succeeded, or false otherwise.
         */
        public boolean commit() throws loginexception {

                if(succeeded == false)
                        return false;

                subject.getprincipals().add(new principaluser(username));
                subject.getprincipals().addall(getuserroles(username));
                
                username = null;
                password = null;

                commitsucceeded = true;
                return true;
        }


        /**
         * this method is called if the logincontext's overall
         * authentication failed. (the relevant required, requisite,
         * sufficient and optional loginmodules did not succeed).
         * <p>
         * if this loginmodule's own authentication attempt succeeded
         * (checked by retrieving the private state saved by the
         * <code>login</code> and <code>commit</code> methods),
         * then this method cleans up any state that was originally
         * saved.
         *
         * @exception loginexception if the abort fails.
         *
         * @return false if this loginmodule's own login and/or commit attempts
         * failed, and true otherwise.
         */
        public boolean abort() throws loginexception {

                if (succeeded == false)
                        return false;
                                                
                if(succeeded == true && commitsucceeded == false) {
                        // login succeeded but overall authentication failed
                        succeeded = false;
                        username = null;
                        password = null;
                } else {
                        // overall authentication succeeded and commit
                        // succeeded, but someone else's commit failed.
                        logout();
                }
                
                return true;
        }


        /**
         * logouts a subject.
         * <p>
         * this method removes the <code>principalexample</code>
         * instances that were added by the <code>commit</code>
         * method.
         *
         * @exception loginexception if the logout fails.
         *
         * @return true if this method succeeded, or false if this
         * loginmodule should be ignored.
         */
        public boolean logout() throws loginexception {

                subject.getprincipals().clear();
                succeeded = false;
                succeeded = commitsucceeded;
                username = null;
                password = null;
                
                return true;
        }

        
        /**
         * searches the users xml file for the specified
         * userid and password.
         */
        private boolean isvaliduser(string uid, char&#91;&#93; passwd) {
                try {
                        /*get userid and password from db */
                        string name=&quot;tyrone1979&quot;;
                        string password=&quot;197913&quot;;
                        if (uid.equals(name)){
                                if (password.equals(new string(password)))
                                        return true;
                        }

                } catch (exception e) {
                        e.printstacktrace();
                        throw new runtimeexception(e.getmessage());
                }
                return false;
        }


        /**
         * searches the user's group xml file and returns a
         * collection of principalexamples for each group
         * a user is a member of.
         */
        private collection getuserroles(string username) {
                collection collection =null;

                try {
                        /*
                                 get roles from db
                                */
                        arraylist roles=new arraylist();
                        roles.add(new principaluser(&quot;00001&quot;));
                        collection=roles;
                } catch (exception e) {
                        e.printstacktrace();
                        throw new runtimeexception(e.getmessage());
                }

                return collection;
        }

}


4. callback类

public class logincallbackhandler implements callbackhandler {
        
        private string name=null;
        
        private string password=null;
        
        public logincallbackhandler(string name,string password){
                super();
                this.name=name;
                this.password=password;
                
        }
        /**
         * @see callbackhandler#handle(callback&#91;&#93;)
         */
        public void handle(callback&#91;&#93; callbacks) throws ioexception, unsupportedcallbackexception {
                                        
                for (int i = 0; i < callbacks.length; i++) {
                        if (callbacks&#91;i&#93; instanceof textoutputcallback) {
                                textoutputcallback textoutputcallback = (textoutputcallback) callbacks&#91;i&#93;;
                                switch (textoutputcallback.getmessagetype()) {
                                        case textoutputcallback.information :
                                                //system.out.println(textoutputcallback.getmessage());
                                                break;
                                        case textoutputcallback.error :
                                                //system.out.println(&quot;error: &quot; + textoutputcallback.getmessage());
                                                break;
                                        case textoutputcallback.warning :
                                                //system.out.println(&quot;warning: &quot; + textoutputcallback.getmessage());
                                                break;
                                        default :
                                                throw new ioexception(&quot;invalid message type: &quot; + textoutputcallback.getmessagetype());
                                }
                        } else if(callbacks&#91;i&#93; instanceof namecallback) {
                                        // prompt the user for a userid
                                        namecallback nc = (namecallback) callbacks&#91;i&#93;;
                                        nc.setname(this.name);
                        } else if(callbacks&#91;i&#93; instanceof passwordcallback) {
                                        // prompt the user for the password
                                        passwordcallback pc = (passwordcallback) callbacks&#91;i&#93;;

                                        pc.setpassword(this.password.tochararray());
                        } else {
                                throw new unsupportedcallbackexception(callbacks&#91;i&#93;, &quot;invalid callback&quot;);
                        }
                }                                                
        }
}


5.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;);                                        
                        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