tomcat下jaas配置实例

本文介绍如何在Tomcat中使用Java Authentication and Authorization Service (JAAS)自定义Realm进行用户身份验证和授权。详细步骤包括创建自定义LoginModule、Principal子类,配置jaas.config文件,以及在web.xml和server.xml中设置安全约束和Realm。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

声明:以下方式只能帮忙理解知识,如果希望通过步骤跑起来,有一些坑。

1、采用的JDK 1.8

 

一、首先参考tomcate下文档的jaasRealm的配置,注意文档中的两个地方:

Quick Start

To set up Tomcat to use JAASRealm with your own JAAS login module, you will need to follow these steps:

1.    Write your own LoginModule, User and Role classes based on JAAS (see the JAAS Authentication Tutorial and the JAAS Login Module Developer's Guide) to be managed by the JAAS Login Context (javax.security.auth.login.LoginContext) When developing your LoginModule, note that JAASRealm's built-in CallbackHandler +only recognizes the NameCallback and PasswordCallback at present.

2.    Although not specified in JAAS, you should create seperate classes to distinguish between users and roles, extending javax.security.Principal, so that Tomcat can tell which Principals returned from your login module are users and which are roles (see org.apache.catalina.realm.JAASRealm). Regardless, the first Principal returned is always treated as the user Principal.

3.    Place the compiled classes on Tomcat's classpath

4.    Set up a login.config file for Java (see JAAS LoginConfig file) and tell Tomcat where to find it by specifying its location to the JVM, for instance by setting the environment variable: JAVA_OPTS=-DJAVA_OPTS=-Djava.security.auth.login.config==$CATALINA_HOME/conf/jaas.config

5.    Configure your security-constraints in your web.xml for the resources you want to protect

6.    Configure the JAASRealm module in your server.xml

7.    Restart Tomcat 5 if it is already running.

Additional Notes

·   When a user attempts to access a protected resource for the first time, Tomcat 5 will call the authenticate() method of this Realm. Thus, any changes you have made in the security mechanism directly (new users, changed passwords or roles, etc.) will be immediately reflected.

·   Once a user has been authenticated, the user (and his or her associated roles) are cached within Tomcat for the duration of the user's login. For FORM-based authentication, that means until the session times out or is invalidated; for BASIC authentication, that means until the user closes their browser. Any changes to the security information for an already authenticated user will not be reflected until the next time that user logs on again.

·   As with other Realm implementations, digested passwords are supported if the <Realm> element in server.xml contains a digest attribute; JAASRealm's CallbackHandler will digest the password prior to passing it back to the LoginModule

 

二、按照文档Quick Start的顺序先编写jaas’s  code

Role

package bo;

import java.security.Principal;



public class Role

        implements Principal

{

    private String rolename;

    public Role(String rolename)

    {

        this.rolename=rolename;

    }



    /**//**

 * equals

 *

 * @param object Object

 * @return boolean

 * @todo Implement this java.security.Principal method

 */

public boolean equals(Object object){

    System.out.print("object="+object.getClass().toString());

    boolean flag=false;

    if(object==null)

        flag=false;

    if(this==object)

        flag= true;

    if(!(object instanceof Role))

        flag= false;

    if(object instanceof Role)

    {

        Role that = (Role) object;

        if (this.getName().equals(that.getName()))

        {

            flag= true;

        }

    }

    System.out.println("flag="+flag);

    return flag;



}



    /**//**

 * toString

 *

 * @return String

 * @todo Implement this java.security.Principal method

 */

public String toString()

{

    return this.getName();

}



    /**//**

 * hashCode

 *

 * @return int

 * @todo Implement this java.security.Principal method

 */

public int hashCode()

{

    return rolename.hashCode();

}



    /**//**

 * getName

 *

 * @return String

 * @todo Implement this java.security.Principal method

 */

public String getName()

{

    return this.rolename;

}

}

User

package bo;

import java.security.Principal;



public class User

        implements Principal

{

    private String username;

    public User(String username)

    {

        this.username=username;

    }



    /**//**

 * equals

 *

 * @param object Object

 * @return boolean

 * @todo Implement this java.security.Principal method

 */

public boolean equals(Object object)

{

    System.out.print("object="+object.getClass().toString());

    boolean flag=false;

    if(object==null)

        flag=false;

    if(this==object)

        flag= true;

    if(!(object instanceof User))

        flag= false;

    if(object instanceof User)

    {

        User that = (User) object;

        if (this.getName().equals(that.getName()))

        {

            flag= true;

        }

    }

    System.out.println("flag="+flag);

    return flag;

}



    /**//**

 * toString

 *

 * @return String

 * @todo Implement this java.security.Principal method

 */

public String toString()

{

    return this.getName();

}



    /**//**

 * hashCode

 *

 * @return int

 * @todo Implement this java.security.Principal method

 */

public int hashCode()

{

    return username.hashCode();

}



    /**//**

 * getName

 *

 * @return String

 * @todo Implement this java.security.Principal method

 */

public String getName()

{

    return this.username;

}



}
TestLoginMoudle
package bo;

import java.util.Date;
import java.util.Map;



import javax.security.auth.Subject;

import javax.security.auth.callback.Callback;

import javax.security.auth.callback.CallbackHandler;

import javax.security.auth.callback.NameCallback;

import javax.security.auth.callback.PasswordCallback;

import javax.security.auth.login.FailedLoginException;

import javax.security.auth.login.LoginException;

import javax.security.auth.spi.LoginModule;



public class TestLoginMoudle implements LoginModule{



//     initial state

    private Subject subject;



    private CallbackHandler callbackHandler;



    private Map sharedState;



    private Map options;



    // 配置选项.

    private boolean debug = false;



    // 鉴别状况

    private boolean succeeded = false;



    private boolean commitSucceeded = false;



    // 用户名和用户密码.

    private String username;



    private char[] password;



    // 用户的Principal

    private User user;

    private Role role;



    /**//**

     * initialize

     *

     * @param subject Subject

     * @param callbackHandler CallbackHandler

     * @param map Map

     * @param map3 Map

     * @todo Implement this javax.security.auth.spi.LoginModule method

     */

    public void initialize(Subject subject, CallbackHandler callbackHandler,

                           Map map, Map map3)

    {

        this.subject = subject;

        this.callbackHandler = callbackHandler;

        this.sharedState = map;

        this.options = map3;

    }



    /**//**

     * login

     *

     * @return boolean

     * @throws LoginException

     * @todo Implement this javax.security.auth.spi.LoginModule method

     */

    public boolean login() throws LoginException{

        //提示输入用户名和密码;

        if (callbackHandler == null){

            throw new LoginException("No CallBackHandler!");

        }

        Callback[] callbacks = new Callback[2];

        callbacks[0] = new NameCallback("user name");

        callbacks[1] = new PasswordCallback("password", false);

        try{

            callbackHandler.handle(callbacks);

            username = ( (NameCallback) callbacks[0]).getName();

            password = ( (PasswordCallback) callbacks[1]).getPassword();

            System.out.println(new Date().toLocaleString() + "username=" + username);

            System.out.println(new Date().toLocaleString() + "password=" + new String(password));

        }

        catch (Exception e)

        {

            e.printStackTrace();

        }

        // 检验用户名和用户密码.

        boolean isuser = false;

        boolean ispass = false;



        //应该调用ORM操作数据对比用户名和密码;



        if (username.equals("hello"))

        {

            isuser = true;

            String pw_str = new String(password);

            if (pw_str.equals("hello"))

            {

                System.out.println(new Date().toLocaleString() + "Login succesed!");

                ispass = true;

                succeeded = true;

                return succeeded;

            }

        }

        if (!isuser)

        {

            throw new FailedLoginException("User Name Incorrect");

        }

        else

        {

            throw new FailedLoginException("Password Incorrect");

        }

    }



    /**//**

     * commit

     *

     * @return boolean

     * @throws LoginException

     * @todo Implement this javax.security.auth.spi.LoginModule method

     */

    public boolean commit()

            throws LoginException

    {

        if (!succeeded)

        {

            return false;

        }

        else

        {

            user = new User(username);

            role = new Role("guest");

            if (!subject.getPrincipals().contains(user))

            {

                //注册用户

                subject.getPrincipals().add(user);

            }

            if (!subject.getPrincipals().contains(role))

            {

                //注册角色

                subject.getPrincipals().add(role);

            }

            if (debug)

            {

                System.out.println("Add Subject Successed!");

            }

            username = null;

            for (int i = 0; i < password.length; i++)

            {

                password[i] = ' ';

            }

            commitSucceeded = true;

            return true;

        }

    }



    /**//**

     * abort

     *

     * @return boolean

     * @throws LoginException

     * @todo Implement this javax.security.auth.spi.LoginModule method

     */

    public boolean abort()

            throws LoginException

    {

        System.out.println("abort()");

        if (succeeded == false)

        {

            return false;

        }

        else if (succeeded == true && commitSucceeded == false)

        {

            // login succeeded but overall authentication failed

            succeeded = false;

            username = null;

            if (password != null)

            {

                for (int i = 0; i < password.length; i++)

                {

                    password[i] = ' ';

                }

                password = null;

            }

            user = null;

            role = null;

        }

        else

        {

            logout();

        }

        return true;



    }



    /**//**

     * logout

     *

     * @return boolean

     * @throws LoginException

     * @todo Implement this javax.security.auth.spi.LoginModule method

     */

    public boolean logout()

            throws LoginException

    {

        System.out.println("logout()");

        subject.getPrincipals().remove(user);

        subject.getPrincipals().remove(role);

        succeeded = false;

        succeeded = commitSucceeded;

        username = null;

        if (password != null)

        {

            for (int i = 0; i < password.length; i++)

            {

                password[i] = ' ';

            }

            password = null;

        }

        user = null;

        role = null;

        return true;



    }

    public static void main(String[] args) {
        System.out.println("hello world");
    }



}

将上述文件打包在一个jar文件中,jar文件名字可以任意取!

假设$CATALINA_HOME=D:\jakarta-tomcat-5.0.24

当将文件打包后,需要将打包的文件放在$CATALINA_HOME\server\lib下。

如果不将上述文件打包的话,可以直接将上述文件和所属的包放在$CATALINA_HOME\server\classes文件夹下。

三 首先要建立jaas.config文件,我的jaas.config文件内容如下:

MyFooRealm{

bo.TestLoginMoudle required debug=true;

};

在环境变量中配置JAVA_OPTS=-Djava.security.auth.login.config==%CATALINA_HOME%/conf/jaas.config

有多处修改方式,我是通过修改caealina.bat文件实现的

四 在你建的工程web.xml中配置你想保护的资源和验证形势,其代码如下:(注,仅供参考)

<security-constraint>

       <display-name>Tomcat server configuation security constraint</display-name>

       <web-resource-collection>

         <web-resource-name>Protected Area</web-resource-name>

     <!-- Define the context-relative URL(s) to be protected -->

         <url-pattern>/*</url-pattern>

      </web-resource-collection>

      <auth-constraint>

         <!-- Anyone with one of the listed roles may access this area -->

         <role-name>guest</role-name>

      </auth-constraint>

   </security-constraint>

 

<login-config>

      <auth-method>FORM</auth-method>

      <realm-name>jaas role validate</realm-name>

      <form-login-config>

        <form-login-page>/roleValidate/login.jsp</form-login-page>

        <form-error-page>/roleValidate/error.jsp</form-error-page>

      </form-login-config>

</login-config>

 我偷懒没有完全配置,直接借用了tomcat 自带的jsp-example项目。如下图

 五 在tomcat中配置server.xml来修改服务器默认的验证框架:

<Realm className="org.apache.catalina.realm.JAASRealm"                
appName="MyFooRealm"      
userClassNames="bo.User"      
roleClassNames="bo.Role"  debug="99"/>

六 总结

1)Jaas可以用来做为SSO框架

2)  需要做以下事项

              a 实现 自定义JaasRealm

                     i 实现  javax.security.auth.spi.LoginModule方法。

                     ii  构建  Principal 的子类。

                     iii打成jar包放到tomcat_home/server/lib的下。

              b 添加jaas.config 文件,并在tomcat启动参数中添加 Djava.security.auth.login.config 指定到jaas.config的文件位置

              c 在项目下的web.xml 中,通过 security-constraint 安全约束,定义具体的约束条件

              d 在tomcat_home/config/server.xml 中,修改Realm认证为自定义JaasRealm。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值