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

[经验分享] Using JAAS with Tomcat

[复制链接]

尚未签到

发表于 2017-1-24 09:13:30 | 显示全部楼层 |阅读模式
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 instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName(userName);
} else throw new
UnsupportedCallbackException(cb, "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;
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

运维网声明 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-332706-1-1.html 上篇帖子: memcached-session-manager 实现 tomcat session共享 下篇帖子: struts2例子启动tomcat报错
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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

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

扫描微信二维码查看详情

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


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


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


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



合作伙伴: 青云cloud

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