back to index
Using JAAS with Tomcat
Although it is possible to use JAAS within Tomcat as an authentication mechanism (JAASRealm), the flexibility of the JAAS framework is lost once the user is authenticated. This is because the principals are used to denote the concepts of "user" and "role", and are no longer available in the security context in which the webapp is executed. The result of the authentication is available only through request.getRemoteUser() and request.isUserInRole().
This reduces the JAAS framework for authorization purposes to a simple user/role system that loses its connection with the Java Security Policy. This tutorial's purpose is to put a full-blown JAAS authorisation implementation in place, using a few tricks to deal with some of Tomcat's idiosyncrasies.
Basic Design
The goal of the exercise is to be able to wrap the execution of our servlets/jsps in our own JAAS implementation, which allows us to enforce access control with a simple call in our code to AccessController.checkPermission(MyOwnPermission). We achieve this by wrapping each request in a security filter. This is configured in our web.xml. Most of this is covered in widely available JAAS tutorials on the net, so we only have some code fragments here.
web.xml
<filter>
<filter-name>SecurityFilter</filter-name>
<filter-class>security.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Define a Security Constraint on this Application -->
<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>authenticateduser</role-name>
</auth-constraint>
</security-constraint>
<!-- Define the Login Configuration for this Application -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>My Realm</realm-name>
</login-config>
login.conf
To start tomcat in security mode we call startup.sh with the -security flag. Furthermore we need to call our login module by setting $JVM_OPTS to something like -Djava.security.auth.login.config=/usr/local/tomcat/webapps/jaastest/WEB-INF/login.conf
Jaas {
security.HttpLoginModule required debug=true;
};
HttpLoginModule
public class HttpLoginModule implements LoginModule {
...
public boolean commit() throws LoginException {
if (debug)
System.err.println("HttpLoginModule: Commit");
if (!succeeded) {
// We didn't authenticate the user, but someone else did.
// Clean up our state, but don't add our principal to
// the subject
userName = null;
return false;
}
assignPrincipal(new UserPrincipal(userName));
//Based on the username, we can assign principals here
//Some examples for test....
assignPrincipal(new RolePrincipal("authenticateduser"));
assignPrincipal(new RolePrincipal("administrator"));
assignPrincipal(new CustomPrincipal("company1"));
// Clean up our internal state
userName = null;
commitSucceeded = true;
return true;
}
private void assignPrincipal(Principal p)
{
// Make sure we dont add duplicate principals
if (!subject.getPrincipals().contains(p)) {
subject.getPrincipals().add(p);
}
if(debug) System.out.println("Assigned principal "+p.getName()+" of type "+ p.getClass().getName() +" to user "+userName);
}
HttpAuthCallbackHandler
We have Tomcat or Apache do the authentication for us, so we just rely on request.getRemoteUser() to tell us the user name. Feel free to extend...
class HttpAuthCallbackHandler implements CallbackHandler {
private String userName;
public HttpAuthCallbackHandler (HttpServletRequest request) {
userName = request.getRemoteUser();
System.out.println("Remote user is: " + request.getRemoteUser());
}
public void handle(Callback[] cb) throws IOException, UnsupportedCallbackException {
for (int i = 0; i < cb.length; i++) {
if (cb[i] instanceof NameCallback) {
NameCallback nc = (NameCallback) cb[i];
nc.setName(userName);
} else throw new
UnsupportedCallbackException(cb[i], "HttpAuthCallbackHandler");
}
}
}
CustomPolicy
We install a Policy that adds Custom Permissions to the existing PermissionCollection
public class CustomPolicy extends Policy {
private Policy deferredPolicy;
public CustomPolicy(Policy p) {
deferredPolicy = p;
}
public PermissionCollection getPermissions(CodeSource cs) {
PermissionCollection pc = deferredPolicy.getPermissions(cs);
System.out.println("getPermissions was called for codesource");
return pc;
}
public PermissionCollection getPermissions(ProtectionDomain domain) {
PermissionCollection pc = deferredPolicy.getPermissions(domain);
System.out.println("getPermissions was called for domain");
Principal[] principals = domain.getPrincipals();
System.out.println("retrieved " + principals.length + " principals");
for (int i=0; i< principals.length; i++) {
Principal p = principals[i];
System.out.println("This is principal" + p);
CustomPermission[] pms = null;
if (p instanceof CustomPrincipal ) {
System.out.println(p.getName() + " is a CustomPrincipal");
// Get the permissions belonging to the principal here.
// Here we just add an example permission
CustomPermission[] test = { new CustomPermission("AccessToCompany1Building") };
pms = test;
} else {
System.out.println(p.getName() + " is not a CustomPrincipal");
}
// Nothing to do
if (pms == null) continue;
for(int j=0; j< pms.length; j++) {
System.out.println("Adding permission = " + pms[j]);
pc.add(pms[j]);
}
}
System.out.println(pc);
return pc;
}
public void refresh() {
deferredPolicy.refresh();
}
}
SecurityFilter
This is the core of our solution. We install our CustomPolicy here (note that this is definitely not redeployment-safe!). Note that we the feed our authenticated subject into the session. Tomcat then uses this subject when calling your servlets. This is the trick that makes the whole thing work; without it, the Subject is lost.
public class SecurityFilter implements Filter {
public void init(FilterConfig config) throws ServletException {
Policy orgPolicy = Policy.getPolicy();
if (orgPolicy instanceof CustomPolicy) {
// we already did this once upon a time..
System.out.println("Policy is a CustomPolicy,we already did this once upon a time");
} else {
Policy.setPolicy(new CustomPolicy(orgPolicy));
System.out.println("Policy is not a CustomPolicy");
}
}
public void destroy() {
//config = null;
}
public void doFilter(ServletRequest sreq, ServletResponse sres,
FilterChain chain) throws IOException, ServletException {
System.out.println("Starting SecurityFilter.doFilter");
HttpServletResponse response = (HttpServletResponse)sres;
HttpServletRequest request = (HttpServletRequest)sreq;
HttpSession session = request.getSession(true);
Subject subject = (Subject)session.getAttribute("javax.security.auth.subject");
if (subject == null) {
subject = new Subject();
}
session.setAttribute("javax.security.auth.subject", subject);
LoginContext lc = null;
try {
lc = new LoginContext("Jaas", subject, new HttpAuthCallbackHandler(request));
System.out.println("established new logincontext");
} catch (LoginException le) {
le.printStackTrace();
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
return;
}
try {
lc.login();
// if we return with no exception, authentication succeeded
} catch (Exception e) {
System.out.println("Login failed: " + e);
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
return;
}
try {
System.out.println("Subject is " + lc.getSubject());
chain.doFilter(request, response);
} catch(SecurityException se) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, request.getRequestURI());
}
}
}
Testing it out
If you want to test your subject, a simple JSP like the one below is a great help
<%@page import="java.security.*" %>
<%@page import="javax.security.auth.*" %>
<html>
<h1>Hello World!</h1>
<pre>
<% Subject subject = Subject.getSubject(AccessController.getContext()); %>
<b>Subject</b> = <%= subject %>
-----------------------------------------------
<b>RemoteUser</b> = <%= request.getRemoteUser() %>
-----------------------------------------------
<%
out.print("Is user in role \"authenticateduser\"?: ");
if (request.isUserInRole("authenticateduser")) {
out.println("yes");
} else {
out.println("no");
}
%>
-----------------------------------------------
<b>Session Contents</b>
<%
java.util.Enumeration atts = session.getAttributeNames();
while (atts.hasMoreElements()) {
String elem = (String)atts.nextElement();
out.println(elem + " -> " + session.getAttribute(elem));
out.println( );
}
%>
</pre>
</html>
Copyright (c) 2004 Michiel Toneman : rot13(zvpuvry@xbcm.bet)
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. The full text of the license is found at: http://www.gnu.org/copyleft/fdl.html
分享到:
相关推荐
文件中包含 已配置好的tomcat7和jass示例 打包部署后即可运行 还有一份说明文档 tomcat配置的是mac版的,如果是windows的系统请自行修改tomcat启动参数
tomcat下jaas配置实例(文档有不完善的地方) 1、需要修改 bin\startup.bat(根据自己的环境修改) SET JAVA_HOME=C:\programs\Java\jdk1.8.0_211 SET TOMCAT_HOME=C:\programs\apache-tomcat-5.5.20 2、需要修改 bin...
JBOSS security JAAS
As Service-Oriented Architecture (SOA) is now slowly starting to change its status from a buzzword associated with boxes on drawing boards, the early adopters are beginning to look beyond primitive ...
jaas详细配置精讲 tomcat web.xml
jaas.jar jaas.jar jaas.jar
jaas实现,单纯java文件
The last part of the book will deal with some more advanced areas of Tomcat, including Tomcat customization, EJB server integration and using embedded Tomcat. Product Details Paperback: 768 pages ...
jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas j2se例子jaas ...
JAAS JaasDemo JAAS例子
java JAAS登陆验证
JAAS简介及实例.JAAS简介及实例.JAAS简介及实例.JAAS简介及实例.JAAS简介及实例.JAAS简介及实例.JAAS简介及实例.
JAAS简单入门例子
JAAS认证与授权教程,包含本教程的源代码
AAS灵活的Java安全机制
JAAS 本身包括文档和一个lib 目录,其中只有一个jar 文件(jaas.jar)。
原代码 博文链接:https://callan.iteye.com/blog/158392
JAAS in Web Applications主要是关于java 的认证与授权.例子很详细,如果有需要此类功能开发可以联系我,收费2000