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

11 篇文章 0 订阅
4 篇文章 0 订阅

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.

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
牙科就诊管理系统利用当下成熟完善的SSM框架,使用跨平台的可开发大型商业网站的Java语言,以及最受欢迎的RDBMS应用软件之一的Mysql数据库进行程序开发。实现了用户在线查看数据。管理员管理病例管理、字典管理、公告管理、药单管理、药品管理、药品收藏管理、药品评价管理、药品订单管理、牙医管理、牙医收藏管理、牙医评价管理、牙医挂号管理、用户管理、管理员管理等功能。牙科就诊管理系统的开发根据操作人员需要设计的界面简洁美观,在功能模块布局上跟同类型网站保持一致,程序在实现基本要求功能时,也为数据信息面临的安全问题提供了一些实用的解决方案。可以说该程序在帮助管理者高效率地处理工作事务的同时,也实现了数据信息的整体化,规范化与自动化。 管理员在后台主要管理病例管理、字典管理、公告管理、药单管理、药品管理、药品收藏管理、药品评价管理、药品订单管理、牙医管理、牙医收藏管理、牙医评价管理、牙医挂号管理、用户管理、管理员管理等。 牙医列表页面,此页面提供给管理员的功能有:查看牙医、新增牙医、修改牙医、删除牙医等。公告信息管理页面提供的功能操作有:新增公告,修改公告,删除公告操作。公告类型管理页面显示所有公告类型,在此页面既可以让管理员添加新的公告信息类型,也能对已有的公告类型信息执行编辑更新,失效的公告类型信息也能让管理员快速删除。药品管理页面,此页面提供给管理员的功能有:新增药品,修改药品,删除药品。药品类型管理页面,此页面提供给管理员的功能有:新增药品类型,修改药品类型,删除药品类型。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值