This article describes how to secure a JSF2 web application with Java Authentication and Authorization Service (JAAS) and JBoss7.1. It uses a "FORM" authentication method. Users and roles are stored in a mysql database. We also want to use JSF2 tags and Primefaces tags as well, not a plain html form.
1. Introduction
Briefly, JAAS would be provided by the container, ie, JBoss7.1 in our example. In order to handle the login form by our own application code, we need to activate the login process in the login bean, by calling the JAAS login module api. JEE6/Servelet 3.0 provides JAAS api in the HttpServeltRequest object, as follows:
request.login(username, password); request.logout();
So, this results in the login backing bean to get the reference of the HttpServletRequest object and call the login(username, password). Here the username and password would be the form parameters user submitted. This is nothing new.
2. Configurations
JAAS is more about configurations. We need to configure a security domain in JBoss7.1 and secure resources(URLs) in web.xml of our web application. We also need to add a jboss-web.xml to hook up our configured security domain in JBoss7.1 to our web application configurations. In the database, we have two tables "user" and "role". The "user" table would hold username and password etc. The "role" table would hold mappings of "username" to the roles we defined for the web application.
2.1 Configure a JBoss7.1 secuirty domain
This involves adding our security domain to the "standalone.xml " for the standalone server. Open this file and search for "<security-domains>". Under this section, adding our own security domain configuration:
<security-domain name="jwSecureTest"> <authentication> <login-module code="Database" flag="required"> <module-option name="dsJndiName" value="java:/ProJee6DS"/> <module-option name="principalsQuery" value="select password from user where username=?"/> <module-option name="rolesQuery" value="select role, 'Roles' from role where username=?"/> </login-module> </authentication> </security-domain>
Our secrity domain is going to use datasource "java:/ProJee6DS"(u have to configure it. same to the datasource web app uses) to authenticate users. The "principalsQuery" would select user password from table "user" and "rolesQuery" would select the roles that the logged in user would have. Once user logged in successfully, these data would be saved in the login context for the user (-; this is my guess.
2.2 Database tables configuration
So lets add those "user" and "role" tables in database. We have two roles "admin" and "usr".
create table user ( id int, username varchar(20) not null, password varchar(10) not null, email varchar(100) ); create table role ( username varchar(20) not null, role varchar(10) not null ); insert into user values (1, 'j2ee', 'j2ee', null); insert into user values (2, 'jason', 'jason', 'jason@123.com'); insert into role values ('j2ee', 'admin'); insert into role values ('jason', 'usr');
2.3 Configure our web application web.xml
In "web.xml", we have to define the pages/urls to secure. For example, it needs "admin" role to access. We also define the access error page to handle the http "403" error. Note, we need to define it's a Servlet 3.0 web application. Since the JAAS api only available after 3.0
Here's the relevant section:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="ProJee6" version="3.0"> <!-- except for login.jsf, every page requires at lease role "usr", ie, u need to login --> <security-constraint> <web-resource-collection> <web-resource-name>login protected resources</web-resource-name> <url-pattern>/home.jsf</url-pattern> <url-pattern>/tst/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>usr</role-name> <role-name>admin</role-name> </auth-constraint> </security-constraint> <!-- /student/* only accessible to users with role "admin" --> <security-constraint> <web-resource-collection> <web-resource-name>protected resources</web-resource-name> <url-pattern>/student/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <!-- restrict role "usr" to access this page <role-name>usr</role-name> --> <role-name>admin</role-name> </auth-constraint> <!-- uncomment to configure ssl: need to configure https connector. <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> --> </security-constraint> <!-- define auth method "FORM" and our login page --> <login-config> <auth-method>FORM</auth-method> <form-login-config> <form-login-page>/login.jsf</form-login-page> <form-error-page>/login.jsf</form-error-page> </form-login-config> </login-config> ...... <!-- define our http 403 error page --> <error-page> <error-code>403</error-code> <location>/noAccess.jsf</location> </error-page>
2.4 Adding jboss-web.xml
This descriptor is used to hook up the security domain we defined in JBoss "jwSecureTest" to our application. It needs to be packaged into "WEB-INF/jboss-web.xml":
<?xml version="1.0" encoding="UTF-8"?> <jboss-web> <security-domain>java:/jaas/jwSecureTest</security-domain> </jboss-web>
2.5. Implement our login page and its backing bean
We dont need to change our login page at all. Here's it anyway:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui"> <h:head> <title>login page</title> </h:head> <h:body> <p:panel header="Login Panel" style="width:50%"> <h:messages/> <h:form> <h:panelGrid columns="2"> <h:outputLabel value="#{msgs.username}: "/> <h:inputText id="nameId" value="#{loginBean.user.username}" required="true" requiredMessage="username is required"/> <h:outputLabel value="${msgs.password}: "/> <h:inputSecret id="passId" value="#{loginBean.user.password}" required="true" requiredMessage="password is required"/> <!-- call action bean method login() --> <h:panelGroup> <h:commandButton type="submit" value="#{msgs.login}" action="#{loginBean.login}"/> <p:spacer width="20"/> <h:outputText value="are you #{flash.USER.username}?" rendered="#{not empty flash.USER.username}"/> </h:panelGroup> </h:panelGrid> </h:form> </p:panel> </h:body> </html>
But we need to change the backing bean to start the JAAS login process by calling its api:
package com.jxee.action; import java.io.Serializable; import java.security.Principal; import javax.ejb.EJB; import javax.faces.application.FacesMessage; import javax.faces.bean.ManagedBean; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import javax.faces.context.Flash; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import com.jxee.ejb.usr.UserDAO; import com.jxee.model.User; /** * Backing bean for login.xhtml * @ManagedBean used to replace the declaration of the bean in faces-config.xml * <br/>you can give it a name, like @ManagedBean("myBean"), otherwise, it defaults * to the class name with the first character lower cased, eg, "loginBean". So in this * example, it can be accessed in JSF pages like this: #{loginBean.login} */ @ManagedBean @SuppressWarnings("all") public class LoginBean implements Serializable { private static final Logger log = Logger.getLogger(LoginBean.class); // inject EJB UserDAO for accessing database // @EJB private UserDAO userDao; // this is not used when using JAAS private User user = new User(); public User getUser() { return this.user; } public void setUser(User user) { this.user = user; } /** * jaas login */ public String login() { ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest req = (HttpServletRequest) cntxt.getRequest(); try { req.login(this.user.getUsername(), this.user.getPassword()); log.info(">>> user logged in: " + this.user.getUsername()); return "/home.jsf"; } catch(Exception e) { log.error(String.format("login failed. user: %s, due to: %s ", this.user.getUsername(),e.getMessage())); } return "/login.jsf"; } /** * jaas logout */ public String logout() { ExternalContext cntxt = FacesContext.getCurrentInstance().getExternalContext(); HttpServletRequest req = (HttpServletRequest) cntxt.getRequest(); Principal pp = req.getUserPrincipal(); String aname = pp.getName(); try { req.logout(); log.info(">>> user logged out: " + aname); } catch(Exception e) { log.error(String.format("Error logout user %s, due to: %s", aname, e.getMessage())); } return "/login.jsf?faces-redirect=true"; } ...... }
The http 403 error page "/noAccess.xhtml":
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:p="http://primefaces.org/ui" template="/template/template1.xhtml"> <ui:define name="title">home</ui:define> <ui:define name="content"> <p:panel header="Access Error" style="width:60%;border:0px"> <b>#{msgs.noAccess}</b> </p:panel> </ui:define> </ui:composition>
With these configurations, onle users with "admin" role can access the pages "/student/*". This include pages "/student/studentSearch.js" and "student/studentDetails.jsf". That is, according to our database data, user "jason" has no access to these pages.
Next, i'll take a look at prorgammatic approach of JAAS to secure application components. JEE6 provides annotations to test if calling client is in a role to secure the calling of a method.
相关推荐
NULL 博文链接:https://jxee.iteye.com/blog/1596084
它使用 Deltaspike、JSF with Primefaces 和 JBoss Logging。 JBoss 环境设置 概念验证参考环境是 JBoss EAP 6.3GA,需要正确配置 POC 才能按预期工作。 先决条件 安装并配置了 Oracle JDK 7 - 目前是 Oracle JDK 7...
NULL 博文链接:https://jxee.iteye.com/blog/1608820
NULL 博文链接:https://jxee.iteye.com/blog/1575432
JEE企业应用笔记
Restlet所需要的所有jar包 一次下载,以后高枕无忧!
使用 JSF、Spring 和 Mybatis 构建 JEE 应用程序的模板 简单的模式 坚持 国际化 JSF 处理异常 构架 JDK 8 Tomcat 8 / 野蝇 8 / 码头 9 Spring IO 平台 1.1.2(JSF 2.2、Spring 4.1、Hibernate 4.3) MyBatis 3.2...
最新JEE6编程开发模型,详细讲述了JPA,JSF,CDI,EJB等开发技术
JeeWeb敏捷开发平台 QQ交流群: 570062301(满)、522959928 官方网站: 文档地址: 项目演示: 前后端分离版本项目演示: 分离开发前端项目地址: 简介 JeeWeb是一款基于SpringBoot 2+Spring+Mybatis+Hibernate的...
sqoop-1.4.6.2.3.99.0-195.jar org.restlet-2.4.3.jar org.restlet.ext.servlet-2.4.3.jar
You'll explore not just different JEE technologies and how to use them (JSP, JSF, JPA, JDBC, EJB, web services etc.), but also suitable technologies for different scenarios. The book starts with how...
jsf-弹簧-Hibernate使用 JSF、Spring 和 Hibernate 构建 JEE 应用程序的模板简单的模式坚持国际化JSF 处理异常洋葱建筑构架JDK 8 Tomcat 8 / 码头 9 Spring IO 平台(JSF、Hibernate、Spring Data,参见这里 ) 主页...
wicketstuff-jee-web(以前的 wicket.jsp) JEEWebResolver 用于通过自定义 Wicket-Tag 将 Servlet、JSP 和 JSF 内容嵌入到邪恶的 HTML 页面中。 它使用 Wicket 6.x / 7.x 进行测试。 因为 include 用于应用内容,...
jee6-petclinic2 要使用 mysql jndi 资源: 要将 mysql 数据源安装到 Wildfly 8.1 上,请运行“mvn verify -Pds” 在 conf/persistence.xml jta-data-source 和 comment 属性中取消注释。
开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32开发工具 eclipse-jee-mars-2-win32...
NULL 博文链接:https://jxee.iteye.com/blog/1670378
bee-jee-test-task:MVC简单应用
jee 入门(深入浅出学习JEE)系列精品教程
JEE2实现文件上传
JeeWeb是一款基于SpringMVC+Spring+Hibernate的敏捷开发系统;它是一款具有代码生成功能的智能快速开发平台;是以Spring Framework为核心容器,Spring MVC为模型视图控制器,Hibernate为数据访问层, Apache Shiro为...