`
george.gu
  • 浏览: 73898 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

JAAS: Java Authentication and Authorization Service

 
阅读更多

Subject:

 

/**
 * <p> A <code>Subject</code> represents a grouping of related information
 * for a single entity, such as a person.
 * Such information includes the Subject's identities as well as
 * its security-related attributes
 * (passwords and cryptographic keys, for example).
 *
 * <p> Subjects may potentially have multiple identities.
 * Each identity is represented as a <code>Principal</code>
 * within the <code>Subject</code>.  Principals simply bind names to a
 * <code>Subject</code>.  For example, a <code>Subject</code> that happens
 * to be a person, Alice, might have two Principals:
 * one which binds "Alice Bar", the name on her driver license,
 * to the <code>Subject</code>, and another which binds,
 * "999-99-9999", the number on her student identification card,
 * to the <code>Subject</code>.  Both Principals refer to the same
 * <code>Subject</code> even though each has a different name.
 *
 * <p> A <code>Subject</code> may also own security-related attributes,
 * which are referred to as credentials.
 * Sensitive credentials that require special protection, such as
 * private cryptographic keys, are stored within a private credential
 * <code>Set</code>.  Credentials intended to be shared, such as
 * public key certificates or Kerberos server tickets are stored
 * within a public credential <code>Set</code>.  Different permissions
 * are required to access and modify the different credential Sets.
 *
 * <p> To retrieve all the Principals associated with a <code>Subject</code>,
 * invoke the <code>getPrincipals</code> method.  To retrieve
 * all the public or private credentials belonging to a <code>Subject</code>,
 * invoke the <code>getPublicCredentials</code> method or
 * <code>getPrivateCredentials</code> method, respectively.
 * To modify the returned <code>Set</code> of Principals and credentials,
 * use the methods defined in the <code>Set</code> class.
 * For example:
 * <pre>
 *	Subject subject;
 *	Principal principal;
 *	Object credential;
 *
 *	// add a Principal and credential to the Subject
 *	subject.getPrincipals().add(principal);
 *	subject.getPublicCredentials().add(credential);
 * </pre>
 *
 * <p> This <code>Subject</code> class implements <code>Serializable</code>.
 * While the Principals associated with the <code>Subject</code> are serialized,
 * the credentials associated with the <code>Subject</code> are not.
 * Note that the <code>java.security.Principal</code> class
 * does not implement <code>Serializable</code>.  Therefore all concrete
 * <code>Principal</code> implementations associated with Subjects
 * must implement <code>Serializable</code>.
 *
 * @version 1.123, 05/05/04
 * @see java.security.Principal
 * @see java.security.DomainCombiner
 */

 

 

LoginModule:

 

/**
 * <p> <code>LoginModule</code> describes the interface
 * implemented by authentication technology providers.  LoginModules
 * are plugged in under applications to provide a particular type of
 * authentication.
 *
 * <p> While applications write to the <code>LoginContext</code> API,
 * authentication technology providers implement the
 * <code>LoginModule</code> interface.
 * A <code>Configuration</code> specifies the LoginModule(s)
 * to be used with a particular login application.  Therefore different
 * LoginModules can be plugged in under the application without
 * requiring any modifications to the application itself.
 *
 *...
*/
 

 

PasswordLoginModule.java:

 

package com.wgu.jaas;

import java.io.IOException;
import java.security.Principal;
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.callback.UnsupportedCallbackException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

public class PasswordLoginModule implements LoginModule {

	public static final String USER_NAME = "jaas";

	/*
	 * A <code>Subject</code> represents a grouping of related information for
	 * a single entity, such as a person. It present a entity who will
	 * manipulate the system.
	 */
	private Subject mySubject;

	private CallbackHandler myCallbackHandler;

	private String username;

	private char[] password;

	private boolean loginSucceeded = false;

	private boolean commitSucceeded = false;

	/*
	 * This interface represents the abstract notion of a principal, which can
	 * be used to represent any entity, such as an individual, a corporation,
	 * and a login id.
	 * 
	 */
	private Principal myPrincipal;

	/**
	 * abort() will be called if overall login failed.
	 */
	public boolean abort() throws LoginException {
		return false;
	}

	/**
	 * This is called once the login successed.
	 */
	public boolean commit() throws LoginException {
		if (!this.loginSucceeded) {
			return false;
		}
		myPrincipal = new PrincipalImpl(username);

		// create a Principal and add it to Subject.
		if (!mySubject.getPrincipals().contains(myPrincipal)) {
			mySubject.getPrincipals().add(myPrincipal);
		}

		username = null;
		clearPassword();
		commitSucceeded = true;
		return true;
	}

	/**
	 * Initialize the LoginModule according to configuration.
	 */
	public void initialize(Subject subject, CallbackHandler callbackHandler,
			Map<String, ?> sharedState, Map<String, ?> options) {
		this.mySubject = subject;
		this.myCallbackHandler = callbackHandler;
		loginSucceeded = false;
		commitSucceeded = false;
		username = null;
		clearPassword();
	}

	private void clearPassword() {
		if (this.password == null) {
			return;
		}

		for (char c : password) {
			c = (char) ' ';
		}

		password = null;
	}

	/**
	 * Attempt to log a user in.
	 */
	public boolean login() throws LoginException {
		if (myCallbackHandler == null) {
			throw new LoginException("No CallbackHandler defined.");
		}

		/*
		 * Implementations of this interface are passed to a <code>CallbackHandler</code>,
		 * allowing underlying security services the ability to interact with a
		 * calling application to retrieve specific authentication data such as
		 * usernames and passwords, or to display certain information, such as
		 * error and warning messages.
		 */
		Callback[] callbacks = new Callback[2];
		callbacks[0] = new NameCallback("UserName");
		callbacks[1] = new PasswordCallback("Password", false);

		try {
			myCallbackHandler.handle(callbacks);
			username = ((NameCallback) callbacks[0]).getName();
			char[] tempPsw = ((PasswordCallback) callbacks[1]).getPassword();
			password = new char[tempPsw.length];
			System.arraycopy(tempPsw, 0, password, 0, tempPsw.length);
			((PasswordCallback) callbacks[1]).clearPassword();
		} catch (IOException e) {
			throw new LoginException(e.getMessage());
		} catch (UnsupportedCallbackException e) {
			throw new LoginException(e.getMessage());
		}

		// we can update this component to check user/psw against database.
		if (username.equals(USER_NAME) && password.length == USER_NAME.length()) {
			loginSucceeded = true;
			return true;
		} else {
			loginSucceeded = false;
			username = null;
			clearPassword();
			return false;
		}
	}

	/**
	 * Logout user. It will remove Principal from Subject.
	 */
	public boolean logout() throws LoginException {
		mySubject.getPrincipals().remove(myPrincipal);
		loginSucceeded = false;
		commitSucceeded = false;
		username = null;
		clearPassword();
		myPrincipal = null;
		return true;
	}

	public static void main(String[] args) {
		char[] a = { 'a', 'b', 'c' };
		char[] b = a;

		// a = null;

		for (char c : a) {
			c = (char) ' ';
		}

		for (char c : b) {
			System.out.println(c);
		}
	}
}
 

 

UserNamePasswordCallbackHandler.java:

 

/**
 * 
 */
package com.wgu.jaas;

import java.io.IOException;

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.callback.UnsupportedCallbackException;

/**
 * @author wgu
 * 
 */
public class UserNamePasswordCallbackHandler implements CallbackHandler {

	String username;

	char[] password;

	public UserNamePasswordCallbackHandler(String username, char[] password) {
		this.username = username;
		this.password = password;
	}

	public void handle(Callback[] callbacks) throws IOException,
			UnsupportedCallbackException {
		for (Callback callback : callbacks) {
			if (callback instanceof NameCallback) {
				NameCallback nameCb = (NameCallback) callback;
				nameCb.setName(username);
			} else if (callback instanceof PasswordCallback) {
				PasswordCallback pswCb = (PasswordCallback) callback;
				pswCb.setPassword(password);
			}
		}
	}

}
 

 

PrincipalImpl.java:

 

/**
 * 
 */
package com.wgu.jaas;

import java.io.Serializable;
import java.security.Principal;

/**
 * @author Administrator
 * 
 */
public class PrincipalImpl implements Principal, Serializable {
	private String name;

	public PrincipalImpl(String name) {
		this.name = name;
	}

	@Override
	public int hashCode() {
		return name.hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		final PrincipalImpl other = (PrincipalImpl) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public String getName() {
		return name;
	}

	public String toString() {
		return getName();
	}
}

 

 

JAASTest.java:

 

/**
 * 
 */
package com.wgu.jaas;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

/**
 * @author wgu
 * 
 */
public class JAASTest {
	/**
	 * We have to config "-Djava.security.auth.login.config=jaas.config" to
	 * specify configuration file.
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		LoginContext lc = new LoginContext("JAASSample",
				new UserNamePasswordCallbackHandler());
		try {
			lc.login();
		} catch (LoginException e) {
			// Authentication failed.
		}

		// Authentication successful, we can now continue.
		// We can use the returned Subject if we like.
		Subject sub = lc.getSubject();
		System.out.println(sub);
	}
}
 

 

 

jaas.config:

 

JAASSample {
	com.wgu.jaas.PasswordLoginModule required
        option1="I am option";
};
 

 

JAASPriveligedActionExample.java:

 

package com.wgu.jaas;

import java.security.PrivilegedAction;

public class JAASPriveligedActionExample implements PrivilegedAction {

	public Object run() {
		System.out.println("Secret text: "
				+ JAASAuthorizationExample.getSecretText());

		return null;
	}

}
 

 

JAASAuthorizationExample.java:

package com.wgu.jaas;

import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Principal;

import javax.security.auth.Subject;
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;

public class JAASAuthorizationExample {
	private static final String NO_PRINCIPAL = "NO_PRINCIPAL";

	public static String getSecretText() {
		AccessControlContext context = AccessController.getContext();
		Subject sub2 = Subject.getSubject(context);
		if (sub2 == null) {
			return NO_PRINCIPAL;
		}

		for (Principal p : sub2.getPrincipals()) {
			if (p.getName().equals(PasswordLoginModule.USER_NAME)) {
				return "PRINCIPAL_OK";
			}
		}

		return NO_PRINCIPAL;
	}

	/**
	 * We have to config "-Djava.security.auth.login.config=jaas.config" to
	 * specify configuration file.
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		LoginContext lc = new LoginContext("JAASSample",
				new UserNamePasswordCallbackHandler());
		try {
			lc.login();
		} catch (LoginException e) {
			// Authentication failed.
		}

		// Authentication successful, we can now continue.
		// We can use the returned Subject if we like.
		Subject sub = lc.getSubject();
		/*
		 * Perform work as a particular <code>Subject</code>.
		 * 
		 */
		Subject.doAs(sub, new JAASPriveligedActionExample());
	}

}
 

 

分享到:
评论

相关推荐

    Seam security

    5. JAAS:Java Authentication and Authorization Service (JAAS)是J2EE遗留下来的认证和授权框架,尽管它有些复杂,且配置晦涩,并且过于依赖于容器,文档也不完善,但它是一个可插拔的解决方案。在Seam Security中...

    JAAS:灵活的Java安全机制

    Java Authentication and Authorization Service (JAAS, Java验证和授权API)为Java应用程序提供了一种扩展标准Java 2安全模型的方法。通过添加验证主题(即用户或其他实体)的能力以及基于验证标识的授权功能,JAAS...

    JAAS灵活的Java安全机制

    Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现用户认证和权限授权的一个核心组件。它为开发者提供了一种灵活的方式来实现安全控制,确保只有经过验证和授权的用户能够访问敏感资源或...

    Using JAAS in Java EE and SOA Environments

    **Java Authentication and Authorization Service(JAAS)** 是Java平台提供的一个强大的安全框架,用于实现用户身份验证和授权服务。随着服务导向架构(SOA)逐渐从概念阶段向实际应用过渡,那些早期采用者开始...

    基于JAAS的Java安全编程

    JAAS(Java Authentication and Authorization Service,Java认证与授权服务)是Sun Microsystems为Java 2平台开发的一套安全框架扩展,旨在加强Java应用程序的安全性。JAAS是JDK 1.3的标准组件,并在JDK 1.4中得到...

    java软件包文件 jaas.jar

    Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的关键组件,它提供了一种框架,用于在Java应用程序中实现认证(Authentication)和授权(Authorization)。`jaas.jar` 文件是这个...

    JAAS In Action

    JAAS, the Java Authentication and Authorization Service, has been a standard part of the Java security framework since version 1.4 version and was available as an optional package in J2SE 1.3. Before ...

    JAAS(JAVA验证与授权服务)完整示例

    Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全验证和权限管理的重要框架。它为应用程序提供了一种标准化的方式来处理用户身份验证和权限分配,从而确保只有经过验证的用户才能访问受...

    java高手真经_系统架构卷:java.web系统设计与架构

    Java的安全特性,如JAAS(Java Authentication and Authorization Service)和SSL/TLS协议,以及Spring Security等第三方库的使用,都可能是书中涉及的话题。 此外,书中还会介绍如何进行测试驱动开发(TDD),使用...

    Java JAAS安全认证 demo

    Java Authentication and Authorization Service (JAAS) 是Java平台中用于实现用户身份验证和权限管理的核心组件。这个"Java JAAS安全认证 demo"是一个示例项目,旨在帮助开发者理解如何在Java应用中实施安全认证...

    基于Java的两个通用安全模块的设计与实现(源代码+论文).rar

    在Java中,我们可以利用JASPIC(Java Authentication and Authorization Service for Containers)或JAAS(Java Authentication and Authorization Service)框架来实现这些功能。这些服务可以有效地防止未授权的...

    JAAS.rar_Kerberos_jaas_ldap kerberos

    Java Authentication Authorization Service(JAAS,Java验证和授权API)提供了灵活和可伸缩的机制来保证客户端或服务器端的Java程序。Java早期的安全框架强调的是通过验证代码的来源和作者,保护用户避免受到下载...

    JASS 安全验证代码

    JAAS, the Java Authentication and Authorization Service, has been a standard part of the Java security framework since version 1.4 version and was available as an optional package in J2SE 1.3....

    JAAS In Action download

    **Java Authentication and Authorization Service (JAAS) 深入解析** JAAS,全称为Java Authentication and Authorization Service,是Java平台中的一个核心组件,用于处理应用系统的用户身份验证和权限授权。这个...

    Seam安全模块框架SeamSecurity.zip

    Seam Security 中的验证特性是基于JAAS (Java Authentication and Authorization Service)开发的,它提供了用来进行用户身份认证的高度可配置的接口。然而,针对复杂多变的验证需求,Seam Security 提供了一套非常...

    websphere 6 JAAS登陆例子

    这个主题涉及到Java Authentication and Authorization Service (JAAS)的安全框架,以及它如何在企业级应用服务器环境中确保安全登录。 Java Authentication and Authorization Service (JAAS) 是Java平台提供的一...

    java JAAS登陆验证

    Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全性的框架,主要用于用户身份验证和权限授权。在Java应用程序中,尤其是服务器端应用,确保只有合法的用户能够访问资源是至关重要的。...

    wlfullclient.jar(weblogic完整jar包)

    JASS,通常指的是JAAS(Java Authentication and Authorization Service),是Java平台的一部分,用于实现认证和授权功能。JAAS提供了一种框架,使得开发者可以轻松地集成各种安全机制,例如密码验证、数字证书等。...

    JDK16-security-developer-guide.pdf

    1. 认证和授权机制:Java平台提供了多种认证和授权机制,例如JAAS(Java Authentication and Authorization Service)、JACC(Java Authorization Contract for Containers)等。 2. 加密机制:Java平台提供了多种...

    在JAAS基础上的Java安全编程

    JAAS(Java Authentication and Authorization Service),作为Sun Microsystems为增强Java 2平台安全性而推出的一项重要功能,成为了Java开发人员构建安全应用时不可或缺的工具。JAAS不仅为Java应用程序提供了一种...

Global site tag (gtag.js) - Google Analytics