`

jee6 学习笔记 11: Secure JSF2 web app with JAAS and JBoss7.1

阅读更多

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.

 

 

分享到:
评论

相关推荐

    jee6 学习笔记 5 - Struggling with JSF2 binding GET params

    这篇"jee6 学习笔记 5 - Struggling with JSF2 binding GET params"主要探讨了开发者在使用JSF2绑定GET参数时可能遇到的挑战和解决方案。 JSF2是一个基于MVC(模型-视图-控制器)设计模式的Java框架,用于创建交互...

    jee6 学习笔记 6.3 - @Asynchronous

    在Java企业版(Java EE)6中,`@Asynchronous`注解是一个非常重要的特性,它使得开发者可以方便地在应用程序中实现异步处理。这个注解是Java EE并发编程的一部分,主要应用于EJB(Enterprise JavaBeans)环境,用于...

    jee6poc:使用 JEE6 平台的概念证明。 使用 Deltaspike、JSF 和 Primefaces 和 JBoss Logging

    它使用 Deltaspike、JSF with Primefaces 和 JBoss Logging。 JBoss 环境设置 概念验证参考环境是 JBoss EAP 6.3GA,需要正确配置 POC 才能按预期工作。 先决条件 安装并配置了 Oracle JDK 7 - 目前是 Oracle JDK 7...

    jee6 学习系列告一段落,uploaded zipped project after JAAS security

    标题中的“JEE6 学习系列告一段落,uploaded zipped project after JAAS security”表明这是一个关于Java Enterprise Edition(JEE)6的项目,特别关注了Java Authentication and Authorization Service (JAAS)的...

    jee6 学习笔记 1 - 开发环境的配置

    NULL 博文链接:https://jxee.iteye.com/blog/1575432

    JBoss ESB 学习笔记

    ### JBoss ESB 学习笔记知识点概览 #### 一、搭建ESB开发环境 - **工具准备**: - Eclipse-JEE 3.5:集成开发环境,支持Java EE标准,适合企业级应用程序开发。 - jbossesb-server-4.7:JBoss ESB的具体版本,为...

    JEE企业应用笔记

    ### JEE企业应用笔记 #### 一、JSP与Servlet **JSP (Java Server Pages)** 和 **Servlet** 是Java Web开发中的两个核心组件。它们共同构建了动态Web应用程序的基础。 ##### JSP基本语法 在JSP页面中,可以通过...

    JEE6编程模型

    JEE6(Java Platform, Enterprise Edition 6)是Java EE的第六个版本,它在Java EE 5的基础上对Java的企业级应用开发进行了进一步的优化和增强。JEE6不仅包括了Java EE 5的大多数特性,还引入了更多的新功能和技术,...

    jee 入门(深入浅出学习JEE)

    【JEE入门(深入浅出学习JEE)】 Java企业版(Java Enterprise Edition,简称JEE),也称为Java EE,是Oracle公司推出的企业级应用程序开发平台。它为开发分布式、多层架构的Web应用程序提供了全面的框架和服务。JEE...

    Restlet所需要的所有jar包

    Restlet是一款开源的Java框架,专门用于构建RESTful(Representational State Transfer)Web服务。REST是一种轻量级的架构风格,常用于构建高效、可扩展的网络应用程序。本压缩包包含Restlet框架运行所需的全部jar...

    jsf-spring-mybatis:使用 JSF、Spring 和 Mybatis 构建 JEE 应用程序的模板

    使用 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...

    Create a Java EE 6 Application with JSF 2, EJB 3.1, JPA, and NetBeans IDE 7

    我们将深入探讨如何使用Java EE 6中的核心技术——JavaServer Faces 2.0 (JSF),Enterprise Java Beans 3.1 (包括Session Bean和Message-Driven Bean)以及Java Persistence API (JPA),结合NetBeans IDE 7.3来创建一...

    eclipse-jee-2018-09-win32-x86_64.zip

    标题 "eclipse-jee-2018-09-win32-x86_64.zip" 提供的信息表明这是一款针对Java企业级开发的Eclipse集成开发环境(IDE)的2018年9月版本,适用于Windows 32位操作系统、x86_64架构的计算机。Eclipse是一个开源的、跨...

    Java.EE.Development.with.Eclipse.2nd.Edition.178528534

    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...

    Atlas2.3.0依赖: org.restlet/sqoop-1.4.6.2.3.99.0-195

    Restlet是一个轻量级的Java RESTful(Representational State Transfer)Web服务框架。REST是一种软件架构风格,用于构建可伸缩的、分布式的网络应用程序。Restlet库提供了开发RESTful API所需的一系列组件和工具,...

    jee 参考手册 (实用版)

    除了这些核心组件,JEE还包括了其他服务,如JNDI(Java Naming and Directory Interface)用于服务发现,JPA(Java Persistence API)用于对象关系映射,以及JAX-RS(Java API for RESTful Web Services)用于构建...

    JBoss ESB学习笔记1-搭建ESB开发环境.docx

    本篇笔记将详细介绍如何搭建JBoss ESB的开发环境。 首先,我们需要准备的是Eclipse IDE,这里推荐使用Eclipse-JEE 3.5版本,因为该版本对Java EE开发有着良好的支持,同时包含了对各种服务器的集成。如果你还没有...

    ssm+mysql+maven+jeeweb-mybatis

    6. **Jeeweb-Mybatis**:Jeeweb是一个基于Spring Boot、Spring Cloud和SSM的快速开发平台,它包含了很多企业级功能,如权限管理、工作流、报表、图表等。Jeeweb-Mybatis可能是该项目中的核心模块,专注于MyBatis的...

    jboss-3.2.5.zip

    "jboss-3.2.5.zip"是早期的JBoss版本,虽然现在可能已被更现代的版本如WildFly或EAP所取代,但它仍然有其历史价值,尤其对于学习和理解JEE架构以及证书管理系统的运作机制。EJBCA的集成则提供了一套完整的数字证书...

    CursoWebComponents:JEE Web组件课程6

    在这个课程中,学习者将深入理解如何利用JEE 6的特性来构建可重用、自包含的Web界面组件,从而提升开发效率和代码质量。 【Web组件核心概念】 1. **自定义标签(Custom Tags)**: JEE 6引入了自定义标签的概念,...

Global site tag (gtag.js) - Google Analytics