设为首页 收藏本站
查看: 694|回复: 0

[经验分享] Tomcat下的JAAS设置

[复制链接]

尚未签到

发表于 2017-1-23 10:49:52 | 显示全部楼层 |阅读模式
这次项目例子是采用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 = '';
           }
           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++)
              {
       &

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-332440-1-1.html 上篇帖子: tomcat安装为windows服务,查看windows服务器启动时间 下篇帖子: 基于Tomcat开发Portlet
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表