Tomcat下的JAAS设置

本文介绍如何在Tomcat中使用Java Authentication and Authorization Service (JAAS)进行身份验证和授权。通过自定义Login Module、User及Role类,并配置Tomcat以使用JAAS Realm,可以实现灵活且安全的身份管理。
这次项目例子是采用 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;
    }
   
    /**
     * equals
     *
     * @param object Object
     * @return boolean
     * @todo Implements this java.security.Principal method
     */
   
    public boolean equals(Object object)
    {
       System.out.println("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 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: User.java,v 1.1 2007-5-11 12:50:36wesley zhang Exp $
 **/
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.serurity.Principal method
     */
    public boolean equals(Object object)
    {
       System.out.println("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.sercurity.Principal method
     */
    public String toString()
    {
       return this.getName();
    }
   
    /**
     * hashCode
     * @return int
     * @todo Implement this java.sercurity.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 com.jaas;
 
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;
/**
 * Copyright (c) 2005-2007 by BenQGURU Corporation
 * All rights reserved.
 * @author wesley zhang(wesley.zhang@BenQ.com)
 * @version $Id: TestLoginMoudle.java,v 1.1 2007-5-11 13:01:15wesley zhang Exp $
 **/
public class TestLoginMoudle implements LoginModule
{
    private Subject subject;
    private CallbackHandler callbackHandler;
    private Map shareState;
    private Map options;
    //The configuration select
    private boolean debug = false;
    //The state
    private boolean succeeded = false;
    private boolean commitSucceeded = false;
   
    private String username;
    private char [] password;
   
    //User's 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.LoginMoudle method
     */
    public void initialize(Subject subject, CallbackHandler callbackHandler,
           Map map, Map map3)
    {
       // TODO Auto-generated method stub
       this.subject = subject;
       this.callbackHandler = callbackHandler;
       this.shareState = map;
       this.options = map3;
 
    }
 
    /**
     * login
     *
     * @return boolean
     * @throws LoginException
     * @todo Implement this javax.security.auth.spi.LoginMoudle method
     */
    public boolean login() throws LoginException
    {
       // TODO Auto-generated method stub
       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("username="+username);
           System.out.println("password="+new String(password));
       }
       catch(Exception e)
       {
           e.printStackTrace();
       }
       boolean isuser = false;
       boolean ispass = false;
      
       if(username.equals("hello"))
       {
           isuser = true;
           String pw_str = new String(password);
           if(pw_str.equals("hello"))
           {
              System.out.println("login success!");
              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.LoginMoudle method
     */
    public boolean commit() throws LoginException
    {
       // TODO Auto-generated method stub
       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 Succeeded!");
           }
           username = null;
           for(int i=0;i<password.length;i++)
           {
              password[i] = '';
           }
           commitSucceded = true;
           return true;
       }
    }
 
    /**
     * abort
     *
     * @return boolean
     * @throws loginException
     * @todo Implement this javax.security.auth.spi.LoginMoudle method
     */
    public boolean abort() throws LoginException
    {
       // TODO Auto-generated method stub
       System.out.println("abort()");
       if(succeeded == false)
       {
           return false;
       }
       else if(succeeded == true && commitSucceeded == false)
       {
           //login succed but overall authentication failed
           succeeded = false;
           username = null;
           if(password != null)
           {
              for(int i = 0; i<password.length;i++)
              {
       &
采用PyQt5框架与Python编程语言构建图书信息管理平台 本项目基于Python编程环境,结合PyQt5图形界面开发库,设计实现了一套完整的图书信息管理解决方案。该系统主要面向图书馆、书店等机构的日常运营需求,通过模块化设计实现了图书信息的标准化管理流程。 系统架构采用典型的三层设计模式,包含数据存储层、业务逻辑层和用户界面层。数据持久化方案支持SQLite轻量级数据库与MySQL企业级数据库的双重配置选项,通过统一的数据库操作接口实现数据存取隔离。在数据建模方面,设计了包含图书基本信息、读者档案、借阅记录等核心数据实体,各实体间通过主外键约束建立关联关系。 核心功能模块包含六大子系统: 1. 图书编目管理:支持国际标准书号、中国图书馆分类法等专业元数据的规范化著录,提供批量导入与单条录入两种数据采集方式 2. 库存动态监控:实时追踪在架数量、借出状态、预约队列等流通指标,设置库存预警阈值自动提醒补货 3. 读者服务管理:建立完整的读者信用评价体系,记录借阅历史与违规行为,实施差异化借阅权限管理 4. 流通业务处理:涵盖借书登记、归还处理、续借申请、逾期计算等标准业务流程,支持射频识别技术设备集成 5. 统计报表生成:按日/月/年周期自动生成流通统计、热门图书排行、读者活跃度等多维度分析图表 6. 系统维护配置:提供用户权限分级管理、数据备份恢复、操作日志审计等管理功能 在技术实现层面,界面设计遵循Material Design设计规范,采用QSS样式表实现视觉定制化。通过信号槽机制实现前后端数据双向绑定,运用多线程处理技术保障界面响应流畅度。数据验证机制包含前端格式校验与后端业务规则双重保障,关键操作均设有二次确认流程。 该系统适用于中小型图书管理场景,通过可扩展的插件架构支持功能模块的灵活组合。开发过程中特别注重代码的可维护性,采用面向对象编程范式实现高内聚低耦合的组件设计,为后续功能迭代奠定技术基础。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值