https://www.byteslounge.com/tutorials/jaas-authentication-in-tomcat-example
Introduction
Tomcat provides a default JAAS Realm implementation so developers may implement JAAS Login Modules and easily integrate them with the container. In this tutorial we will implement all the required components to put JAAS up and running in Tomcat web container.
This tutorial considers the following software and environment:
- Ubuntu 12.04
- JDK 1.7.0.09
- Tomcat 7.0.35
The Principals
One of the core concepts of JAAS is the existence of users and roles (roles are similar to groups in UNIX systems). Authorization may be issued to specific users or to roles. In JAAS this is concept is translated to Principals: Principals may represent users or roles independently. Let's define User and Role Principals to be used in this example:
package com.byteslounge.jaas;import java.security.Principal;publicclassUserPrincipalimplementsPrincipal{privateString name;publicUserPrincipal(String name){super();this.name = name;}publicvoid setName(String name){this.name = name;}@OverridepublicString getName(){return name;}}
package com.byteslounge.jaas;import java.security.Principal;publicclassRolePrincipalimplementsPrincipal{privateString name;publicRolePrincipal(String name){super();this.name = name;}publicvoid setName(String name){this.name = name;}@OverridepublicString getName(){return name;}}
Basically we are defining two simple Principals, each one of them requiring just a name so they may be promptly identified (a username or a role name). Remember that our principals must implement the java.security.Principal interface.
The Login Module
Now we need to define a Login Module that will actually implement the authentication process. The Login module must implement the javax.security.auth.spi.LoginModule interface:
package com.byteslounge.jaas;import java.io.IOException;import java.util.ArrayList;import java.util.List;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;publicclassBytesLoungeLoginModuleimplementsLoginModule{privateCallbackHandler handler;privateSubject subject;privateUserPrincipal userPrincipal;privateRolePrincipal rolePrincipal;privateString login;privateList<String> userGroups;@Overridepublicvoid initialize(Subject subject,CallbackHandler callbackHandler,Map<String,?> sharedState,Map<String,?> options){ handler = callbackHandler;this.subject = subject;}@Overridepublicboolean login()throwsLoginException{Callback[] callbacks =newCallback[2]; callbacks[0]=newNameCallback("login"); callbacks[1]=newPasswordCallback("password",true);try{ handler.handle(callbacks);String name =((NameCallback) callbacks[0]).getName();String password =String.valueOf(((PasswordCallback) callbacks[1]).getPassword());// Here we validate the credentials against some// authentication/authorization provider.// It can be a Database, an external LDAP, // a Web Service, etc.// For this tutorial we are just checking if // user is "user123" and password is "pass123"if(name !=null&& name.equals("user123")&& password !=null&& password.equals("pass123")){// We store the username and roles// fetched from the credentials provider// to be used later in commit() method.// For this tutorial we hard coded the// "admin" role login = name; userGroups =newArrayList<String>(); userGroups.add("admin");returntrue;}// If credentials are NOT OK we throw a LoginExceptionthrownewLoginException("Authentication failed");}catch(IOException e){thrownewLoginException(e.getMessage());}catch(UnsupportedCallbackException e){thrownewLoginException(e.getMessage());}}@Overridepublicboolean commit()throwsLoginException{ userPrincipal =newUserPrincipal(login); subject.getPrincipals().add(userPrincipal);if(userGroups !=null&& userGroups.size()>0){for(String groupName : userGroups){ rolePrincipal =newRolePrincipal(groupName); subject.getPrincipals().add(rolePrincipal);}}returntrue;}@Overridepublicboolean abort()throwsLoginException{returnfalse;}@Overridepublicboolean logout()throwsLoginException{ subject.getPrincipals().remove(userPrincipal); subject.getPrincipals().remove(rolePrincipal);returntrue;}}
All the implemented methods are inherited from javax.security.auth.spi.LoginModule interface and will be called by Tomcat at specific moments during the authentication process.
The login method is responsible for checking if the credentials provided by the end user are valid. This check is made against any kind of authorization entity: It may be a database, a web service, a LDAP, etc. The developer may implement this credentials check in the way required by some specific use case.
Note: The login method must throw a LoginException in case of authentication failure.
In the presence of a successful authentication it should fetch the roles associated with the authenticating user. In this case we simulated and hard coded the admin role as a fetched role from the credentials provider for the current user.
The commit method is called after a successful login method execution and is responsible to store the user and roles obtained by the login method in the respective Subject and in the form of Principals. As you can see in the above module implementation, during the login method execution the credentials are obtained by the means of a callback. This callback is initialized in the initialize method together with Subject initialization.
The logout method is called when the user logs out of the system (and the application implements a logout mechanism). Finally the abort method is called when the login method fails to authenticate the user (throws a LoginException).
The web application
In this example we will secure a specific folder of a Java web application. The application will be very simple and its structure is the following:

We will be securing the admin folder.
To accomplish this task we must define some configuration elements in web.xml file. These entries go directly under the web-app element:
<security-constraint><web-resource-collection><web-resource-name>Admin</web-resource-name><url-pattern>/admin/*</url-pattern></web-resource-collection><auth-constraint><role-name>admin</role-name></auth-constraint></security-constraint><security-role><role-name>admin</role-name></security-role><login-config><auth-method>BASIC</auth-method><realm-name>Admin</realm-name></login-config>
In security-constraint element we are defining that all resources under /admin folder are protected and only the admin role is granted to access the resources. All existing roles must be also defined in the security-role element. The login-config element defines how the credentials will be asked to the end user. In this example we will use the Basic authentication scheme (you may have different mechanisms like presenting a web form or page to the end user, but that will be covered in other tutorial).
Now we must define a new file named context.xml and place it under:
/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?><Context><RealmclassName="org.apache.catalina.realm.JAASRealm"appName="BytesLoungeLogin"userClassNames="com.byteslounge.jaas.UserPrincipal"roleClassNames="com.byteslounge.jaas.RolePrincipal"/></Context>
Here we define the class that will implement the JAAS realm. We are using Tomcat default implementation: org.apache.catalina.realm.JAASRealm. We also define which classes will implement the user and roles Principals and we set them to be the ones we defined earlier in this tutorial (UserPrincipal and RolePrincipal). The attribute appName defines how the application will be globally identified by Tomcat in what matters to security configuration.
Finally we must define a JAAS configuration file. We will name it jaas.config and we will place it in Tomcat conf folder:
$CATALINA_BASE/conf/jaas.config
The file looks like the following:
BytesLoungeLogin{ com.byteslounge.jaas.BytesLoungeLoginModule required debug=true;};
This file defines the authentication configuration for BytesLoungeLogin application. Note that it's the same name we used in appName inside context.xml file just above.
Launching Tomcat and testing
Now lets launch Tomcat. We must set a JVM argument that tells Tomcat where the application configuration security file is located, the jaas.config file:
You may set this in the startup catalina.sh file.
When the server is up and running and we access the secure resource:
We will see the Basic authentication dialog asking for credentials:

Now we insert the credentials we hard coded in our Login Module. Username: user123 and Password: pass123
We will be presented the secure resource. Access was granted.

The tutorial full source code is available for download at the end of this page.
Logout process
For more information about the user logout process please refer to the following article:
Keep in mind that this tutorial covered BASIC authentication so your browser will store the user credentials until it's closed.
This means that even if you logout the user, as soon a new request is made against a protected resource the browser will send the credentials again and automatically authenticate the user.
If you need to definitely logout the user and force the credentials to be inserted again you should look into form based authentication: JAAS form based authentication in Tomcat example
相关推荐
**Java Authentication and Authorization Service (JAAS) 认证在Mac版Tomcat中的应用** Java Authentication and Authorization Service (JAAS) 是Java平台的核心组件,用于提供安全的用户认证和权限管理。在Mac版...
Java Authentication and Authorization Service (JAAS) 是Java平台中用于安全认证和授权的核心组件。它为开发者提供了一种标准的方式来管理用户的身份验证和访问控制,从而确保应用程序的安全性。在本精讲中,我们...
11. **安全性增强**:Servlet 2.5规范增强了安全特性,如支持JAAS(Java Authentication and Authorization Service)进行用户身份验证和权限控制。 12. **异步处理**:尽管Servlet 2.5并未直接提供异步处理能力,...
内容概要:本文详细介绍了基于多目标粒子群(MOPSO)算法的冷热电联供(CCHP)综合能源系统运行优化的方法和技术细节。文章首先构建了一个涵盖冷、热、电负荷的优化调度模型,该模型不仅考虑了多种能源资源如燃气轮机、电制冷机、锅炉和风光机组,还包括与上级电网的购售电交易。随后,文章展示了MOPSO算法的具体实现步骤,包括粒子初始化、迭代更新、惯性权重调整、非支配排序和拥挤度计算等关键技术环节。此外,文中还讨论了MATLAB仿真平台的优势及其在处理多时间尺度耦合、风光出力波动等方面的应用。最终,通过Pareto前沿分析,揭示了系统在不同条件下的最优运行模式。 适用人群:适用于从事能源系统优化的研究人员、工程师以及对多目标优化算法有兴趣的学习者。 使用场景及目标:①帮助研究人员理解和应用MOPSO算法进行CCHP系统的优化;②为工程师提供具体的代码实现和仿真工具,以便更好地设计和管理实际的能源系统;③促进学术交流和技术进步,推动可持续能源的发展。 其他说明:文章提供了详细的MATLAB代码片段,便于读者理解和复现实验结果。同时,强调了多目标优化在解决复杂能源系统问题中的重要性和优越性。
原始数据集
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 编译闪电般迅速,并发性能卓越,部署轻松简单!Go 语言以极简设计理念和出色工程性能,成为云原生时代的首选编程语言。从 Docker 到 Kubernetes,全球顶尖科技企业都在采用 Go。点击了解 Go 语言的核心优势、实战窍门和未来走向,开启高效编程的全新体验!
数据库
内容概要:本文详细介绍了基于Matlab 2021a的异步电机矢量控制系统中电流滞环控制的实现过程。首先,文章解释了电流环的整体结构,包括定子电流的坐标变换、转矩分量和励磁分量的分离以及旋转变压器模块的应用。接着,展示了电流滞环控制的核心代码,强调了带积分修正的滞环控制机制,并讨论了SVPWM模块的实现技巧。此外,文章探讨了速度环PI参数的自整定设计、谐波分析、磁链观测器的改进方案以及仿真加速技巧。最后,分享了一些实用的调试经验和仿真优化方法,如参数自适应调整、变步长求解器的选择和数据存储格式的优化。 适合人群:从事电机控制领域的研究人员和技术人员,尤其是对异步电机矢量控制和电流滞环控制感兴趣的读者。 使用场景及目标:适用于希望深入了解异步电机矢量控制系统中电流滞环控制实现细节的研究人员和技术人员。目标是帮助读者掌握电流滞环控制的关键技术和调试技巧,提高仿真实践能力。 其他说明:文中提供了丰富的代码片段和调试经验,有助于读者更好地理解和应用所介绍的技术。同时,报告中还包括详细的故障分析和解决方案,确保读者能够避免常见陷阱并顺利进行仿真。
内容概要:本文详细介绍了如何在LabVIEW 2019环境中实现与三菱PLC的通信及其多线程交互。首先探讨了使用OPC和MC两种通讯协议与三菱PLC建立连接的方法,接着讲述了SQLite数据库用于数据存储的具体步骤,然后阐述了JKI状态机框架的应用,最后讲解了通过数组队列实现多线程交互的技术细节。文中不仅提供了具体的代码示例,还分享了许多实用的经验技巧,如异常处理、性能优化等。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些正在使用或计划使用LabVIEW进行PLC通信和数据处理的人群。 使用场景及目标:适用于需要构建高效稳定的工业控制系统的企业和个人开发者。主要目的是帮助读者掌握如何利用LabVIEW平台完成复杂的PLC通信任务,提高系统的可靠性和效率。 其他说明:作者强调了在实际应用过程中需要注意的问题,例如硬件兼容性、网络稳定性、数据安全性等方面的内容,并给出了针对性的解决方案。此外,还提到了一些常见的误区和潜在的风险点,为后续的工作提供了宝贵的参考资料。
计算机视觉_深度学习_图像处理_目标检测_OpenCV_TensorFlow_PyTorch_基于YOLOv5改进算法的高精度实时多目标检测与跟踪系统_用于智能监控_自动驾驶_工业
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 编译闪电般迅速,并发性能卓越,部署轻松简单!Go 语言以极简设计理念和出色工程性能,成为云原生时代的首选编程语言。从 Docker 到 Kubernetes,全球顶尖科技企业都在采用 Go。点击了解 Go 语言的核心优势、实战窍门和未来走向,开启高效编程的全新体验!
内容概要:本文详细介绍了威纶通触摸屏与施耐德ATV12变频器之间的Modbus通讯方法,涵盖硬件接线、参数设置、控制程序编写以及调试技巧。首先,文章讲解了正确的硬件连接方式,强调了接线规范和注意事项,如使用带屏蔽的双绞线并确保正确接地。接着,针对ATV12变频器的具体参数设置进行了详尽说明,包括通信模式的选择、波特率、校验位等重要参数的配置。随后,文章展示了如何在威纶通触摸屏上创建Modbus RTU设备,并提供了具体的配置参数和控制命令示例。此外,文中还分享了一些常见的调试问题及其解决办法,如通讯超时、频率设定异常等。最后,给出了实用的调试建议,如使用串口助手抓包分析和加入通讯心跳检测等功能。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是那些负责PLC编程、HMI界面开发以及设备集成工作的专业人员。 使用场景及目标:适用于需要将威纶通触摸屏与施耐德ATV12变频器进行Modbus通讯连接的实际工程项目中,帮助技术人员顺利完成设备间的通讯配置,确保系统稳定可靠运行。 其他说明:本文不仅提供了详细的理论指导,还结合了丰富的实践经验,能够有效地提高读者在实际工作中解决问题的能力。同时提醒读者,在进行相关操作前务必仔细阅读官方文档,避免因误操作造成不必要的损失。
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 Rust 以内存安全、零成本抽象和并发高效的特性,重塑编程体验。无需垃圾回收,却能通过所有权与借用检查机制杜绝空指针、数据竞争等隐患。从底层系统开发到 Web 服务构建,从物联网设备到高性能区块链,它凭借出色的性能和可靠性,成为开发者的全能利器。拥抱 Rust,解锁高效、安全编程新境界!
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 编译闪电般迅速,并发性能卓越,部署轻松简单!Go 语言以极简设计理念和出色工程性能,成为云原生时代的首选编程语言。从 Docker 到 Kubernetes,全球顶尖科技企业都在采用 Go。点击了解 Go 语言的核心优势、实战窍门和未来走向,开启高效编程的全新体验!
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 Rust 以内存安全、零成本抽象和并发高效的特性,重塑编程体验。无需垃圾回收,却能通过所有权与借用检查机制杜绝空指针、数据竞争等隐患。从底层系统开发到 Web 服务构建,从物联网设备到高性能区块链,它凭借出色的性能和可靠性,成为开发者的全能利器。拥抱 Rust,解锁高效、安全编程新境界!
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 Rust 以内存安全、零成本抽象和并发高效的特性,重塑编程体验。无需垃圾回收,却能通过所有权与借用检查机制杜绝空指针、数据竞争等隐患。从底层系统开发到 Web 服务构建,从物联网设备到高性能区块链,它凭借出色的性能和可靠性,成为开发者的全能利器。拥抱 Rust,解锁高效、安全编程新境界!
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 Rust 以内存安全、零成本抽象和并发高效的特性,重塑编程体验。无需垃圾回收,却能通过所有权与借用检查机制杜绝空指针、数据竞争等隐患。从底层系统开发到 Web 服务构建,从物联网设备到高性能区块链,它凭借出色的性能和可靠性,成为开发者的全能利器。拥抱 Rust,解锁高效、安全编程新境界!
文档支持目录章节跳转同时还支持阅读器左侧大纲显示和章节快速定位,文档内容完整、条理清晰。文档内所有文字、图表、函数、目录等元素均显示正常,无任何异常情况,敬请您放心查阅与使用。文档仅供学习参考,请勿用作商业用途。 编译闪电般迅速,并发性能卓越,部署轻松简单!Go 语言以极简设计理念和出色工程性能,成为云原生时代的首选编程语言。从 Docker 到 Kubernetes,全球顶尖科技企业都在采用 Go。点击了解 Go 语言的核心优势、实战窍门和未来走向,开启高效编程的全新体验!
内容概要:本文详细介绍了直流无感无刷电机的方波控制方法及其初始位置检测方案。主要内容涵盖ADC和比较器结合用于初始位置检测的技术细节,包括代码示例;多种控制方式如开环控制、速度环控制和双闭环控制的具体实现;通信部分采用串口进行数据交换;多重保护机制确保系统的安全可靠;以及启动方式的选择和优化。此外,还讨论了一些硬件特色,如休眠电路和防打火电路的设计。 适合人群:从事电机控制系统设计的研发工程师和技术爱好者,尤其是对直流无感无刷电机有研究兴趣的专业人士。 使用场景及目标:适用于需要深入了解直流无感无刷电机控制原理的研究人员,帮助他们掌握具体的实现技术和优化技巧,从而应用于实际项目中,提高电机控制系统的性能和可靠性。 其他说明:文中提供了大量实用的代码片段和实践经验,强调了实际应用中的注意事项和调试技巧,对于解决常见问题非常有帮助。