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

本文介绍如何使用Java Authentication and Authorization Service (JAAS) 和 JBoss 7.1为JSF 2应用程序提供安全保护。通过配置安全域、数据库表、web.xml等实现FORM认证方法,并展示了具体的实现步骤。

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.

 

 

【无人机】基于改进粒子群算法的无人机路径规划研究[和遗传算法、粒子群算法进行比较](Matlab代码实现)内容概要:本文围绕基于改进粒子群算法的无人机路径规划展开研究,重点探讨了在复杂环境中利用改进粒子群算法(PSO)实现无人机三维路径规划的方法,并将其与遗传算法(GA)、标准粒子群算法等传统优化算法进行对比分析。研究内容涵盖路径规划的多目标优化、避障策略、航路点约束以及算法收敛性和寻优能力的评估,所有实验均通过Matlab代码实现,提供了完整的仿真验证流程。文章还提到了多种智能优化算法在无人机路径规划中的应用比较,突出了改进PSO在收敛速度和全局寻优方面的优势。; 适合人群:具备一定Matlab编程基础和优化算法知识的研究生、科研人员及从事无人机路径规划、智能优化算法研究的相关技术人员。; 使用场景及目标:①用于无人机在复杂地形或动态环境下的三维路径规划仿真研究;②比较不同智能优化算法(如PSO、GA、蚁群算法、RRT等)在路径规划中的性能差异;③为多目标优化问题提供算法选型和改进思路。; 阅读建议:建议读者结合文中提供的Matlab代码进行实践操作,重点关注算法的参数设置、适应度函数设计及路径约束处理方式,同时可参考文中提到的多种算法对比思路,拓展到其他智能优化算法的研究与改进中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值