这次项目例子是采用struts+hibernate来搭建的,其目的是为了实现jaas在tomcate中的简化实现。在参考了很多资源后,发现利用现有框架和服务器来实现身份的验证和授权是最简单的途径,所以这次我采用的是在tomcat提供的jaas验证框架下实现jaas。虽然这个框架的功能很有限,但结合struts的授权机制就可以满足中等项目的需求了。
一
首先参考tomcat下文档的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 com.jaas;
import java.security.Principal;
/**
* Copyright (c) 2005-2007 by BenQGURU Corporation
* All rights reserved.
* @author wesley zhang(wesley.zhang@BenQ.com)
* @version $Id: Role.java,v 1.1 2007-5-11 12:36:57wesley zhang Exp $
**/
public class Role implements Principal
{
private String rolename;
public Role(String rolename)
{
this.rolename = rolename;
}