顯示具有 Spring3 標籤的文章。 顯示所有文章
顯示具有 Spring3 標籤的文章。 顯示所有文章

21 3月 2011

Spring Security (3) Basic Configuration fo <authentication-provider>

<authentication-manager>共本上提供了兩種Authentication Provider,一個是authentication-provider,另一個是ldap-authentication-provider

預設的authentication-provide就是採用DaoAuthenticationProvider,有三種基本的帳號密碼檢核與提供人員資料方式

  • user-service:建立一個in-memory的UserDetailService,帳密可以自properties file載入或在xml以<user>建立
  • jdbc-user-service:Spring Security提供了SQL Schema,所以相關的帳密可以自DB載入,只要給jdbc-user-service一個DataSource就可以使用,或是現有欄位定稱與Spring Security不同,那也可以透過提供users-by-username-query、authorities-by-username-query等SQL來取得資料。
  • ldap-user-service:再明顯不過了吧,透過ldap取得帳密資料,在預設的情形下是沒意義的....

通常DB裡存的密碼不會是明碼(如果真的是明碼....),所以Spring Security也提供了基本的編碼方式,像sha、md5都有支援,我們可以透過<password-encoder hash="type">來設定這個authentication provider要用哪種編碼;如果我們的編碼方式不在Spring Security的支援範圍之內,也可以自行提供一個PasswordEncoder的實作。

如果可以完全接受SpringSecurity提供的Schema作為系統的帳密設定,那當然是很不錯的一件事,但我想這種事不太容易發生...所以修改的方式通常有二,一是自已提供UserDetailsService的實作將user service換掉,二是用自已的Authentication Provider實作,直接把authentication provider換掉囉。不過換Authentication Provider的原因通常不是因為帳密的DB Schema不同,通常是因為檢核的方式不同而更換,看看Spring Security提供的其他Authentication Provider名稱就知道,像JaasAuthenticationProvider、OpenIDAuthenticationProvider、CasAuthenticaionProvider等就知道需要更換Authentication Provider大約是在什麼情形才需要更動。

 

 

20 3月 2011

Spring Security (2) Basic Configuration of <http>

看過先前的說明應該會有些困惑,我們應該先稍為拆解一下<http>
<http auto-config='true'> 代表了三個預設定設定

  • <form-login>
  • <http-basic>
  • <logout>

<form-login>代表要使用基本的Form-based authentication,但由於沒有指定登入的頁面,所以SpringSecurity會直接採用內建的Servlet產生登入的頁面,如果只是展示一下系統,當然沒問題,但真實在使用的系統應該沒辦法接受,所以直接加上<form-login login-page="/your_login.jsp" />這樣的設定就可以改用目前系統使用的登入頁面,但由於其他設定都沒動,所以form的欄位及action url仍有一定的要求,action仍必需是“/j_spring_security_check“,account的欄位名稱必需是“j_username“,password欄位名稱必需是“j_password“。
form-login還可以設定其他的參數,像login-processing-url代表action要送出的url,default-target-url代表登入成功後要轉的url,authentication-failure-url代表登入失敗後要轉入的url,always-use-default-target設定為true則代表登入成功或失敗都要轉入default-target-url。
比較有趣的是authentication-success-handler-ref與 authentication-failure-handler-ref,這兩個參數不應該與default-target-url、authentication-failure-url共用,這兩個handler-rul的設定代表啟用AuthenticationSuccessHandler與AuthenticationFailureHandler,如果想實現轉入登入前的那一頁用這個設定會很容易達成。

<http-basic>則代表使用HTTP basic authentication header,主要是將帳密用冒號(:)組合,再以base64編碼後送出,這個設定讓系統可以很容易地支援REST的程式。

<logout>代表起用Logout Filter,就SpringSecurity認為,每個系統都應該要有一個Logout Filter才對,比較form-login,當然也可以設定logout-url、logout-success-url及success-handler-rel,另一項是invalidate-session,若設定為true,在登出的同時就會令session失效。

 

18 3月 2011

Spring Security (1) Basic Configuration

一個對外的系統通常有權限設定,主要的需求通常就是兩個

  • 判斷目前的操作人員是誰
  • 人員是否可以進行這個操作

Spring Security提供了一個快速而有彈性的方法可以處理上述兩個需求,當然,有彈性通常也代表較多的設定與較複雜的設計....

我們先假設一個基本的網頁系統權限需求,除index.jsp外,其他的頁面存取都必需要是登入後才能看到,但/admin.jsp則必需是具有admin角色的人員才能看到。

web.xml

第一步當然是載入Spring的設定檔....
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
再來就是利用Spring的filter來檢查url及使用者,設定welcome file主要是讓url為"/"的request直接送到index.jsp
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

接下來就是spring security的設定了,先用最基本的方式,由Spring提供登入的頁面,我們只要提供哪些url需要被檢查,登入的帳號密碼資料即可。

<http auto-config='true'>
    <intercept-url pattern="/" filters="none" />
    <intercept-url pattern="/admin.jsp" access="ROLE_ADMIN" />
    <intercept-url pattern="/**" access="ROLE_USER" />
</http>
<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="admin" password="admin" authorities="ROLE_USER, ROLE_ADMIN" />
            <user name="user" password="user" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>
<http>的<intercept-url>指出哪些url需要被檢查,像"/admin.jsp"就要是具有"ROLE_ADMIN"角色的人才能進人,而除了“/“之外的資源全部需要登入後才能使用。
<user-service>則是提供了帳密及角色的資料。

接下來在browser上試著要進入系統,你會發現除了"/"之外,都會跳出一個登入頁面 Spring Login
可以試著用admin或user的帳號進入。  

這就是最基本的Spring Security 體驗....

25 2月 2011

Startup MX4J HttpAdaptor with Spring

我用JMX用的並不多,多半而言就是拿來控制Logger 的Level,最多加個清Cache,其餘就沒什麼特別在意的。
控制的介面用jconsole多半還過得去,部份案子還是會使用mx4j的HttpAdaptor來建立Web的操作介面,只是在使用上,要自動帶起HttpAdaptor還是有些困擾。

先看看MX4J 的HttpAdaptor,

public void start() throws IOException {
    final Logger logger = getLogger();
    if (server != null) {
         serverSocket = createServerSocket();
         .....
    } else {
        if (logger.isEnabledFor(Logger.INFO)) logger.info("Start failed, no server target server has been set");
    }
}
呼叫start()後,HttpAdaptor就可以提供Web的操作介面。
不過HttpAdaptor一開始就會先確認MBeanServer "server" 的有無,如果沒有就會寫個Log然後結束。
而這個MBeanServer什麼時候會被加進來呢?
是依JMX規格MBeanRegistration,執行preRegister()後才會帶進來,所以如果想在Spring的設定檔裡,加個init-method="start",是無法讓這個Adaptor正常提供Web操作。

那就看看Spring MBeanExporter的原始碼是如何操作MBean的Lifecycle,看到MBeanExporterLinstener這Interface,所以我們可以透過這interface讓系統自動帶起HttpAdaptor;但實際上執行有點困難,因為Spring 2.5以後提供了一個context:mbean-server,可以直接取得系統中現有的MBeanServer或是自行建立一個,所以比較無從加入MBeanExporterLinstener到MBeanServer中。

最後想想,還是從MBeanRegistration這個介面下手,所以直接extend HttpAdaptor後override postRegister()....

 

public class AutostartHttpAdaptor extends HttpAdaptor {
 
 private static final Logger logger = LoggerFactory.getLogger(AutostartHttpAdaptor.class);
 @Override
 public void postRegister(Boolean registrationDone) {
  super.postRegister(registrationDone);
  
  if (!registrationDone) {
   logger.warn("HttpAdaptor should not be invoked start() without registration success.");
   return;
  }
  
  logger.info("Post Register HttpAdaptor('"+registrationDone+"'):");

  try {
   this.start();
  } catch (IOException e) {
   logger.error("HttpAdaptor startup has been failed.", e);
  }
 }

 @Override
 public void postDeregister() {
  super.postDeregister();
  logger.info("Post Deregister HttpAdaptor():");
  this.stop();
 }
 
}

09 11月 2010

Spring MVC (1)

因為專案需要,但是專案沒有wiki的系統(說來Redmine真的不錯用!),就稍為利用這裡記錄關於SpringMVC想說明的部份

(1)library
要開始一個SpringMVC很容易,第一請先建立一個web project,要利用mvn eclipse:eclipse或直接在ide裡開都ok,pom.xml裡的dependency只需要

 <dependencies>
  <dependency>
   <groupid>org.springframework</groupid>
   <artifactid>spring-webmvc</artifactid>
   <version>3.0.5.RELEASE</version>
  </dependency>
  <dependency>
   <groupid>javax.servlet</groupid>
   <artifactid>jstl</artifactid>
   <version>1.2</version>
  </dependency>
 </dependencies> 

(2)web.xml
web.xml也很容易,只要將SpringMVC要用的front controller -- DispatcherServlet喚起就可以,而serlvet-mapping就看你高興,不喜歡以.do結尾也可用asp,php或html來混淆他人...下列的設定代表所有http://host/module/XXXX.do的url皆會由Spring的DispatcherServlet處理

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee">
 <servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>*.do</url-pattern>
 </servlet-mapping>
</web-app> 


(3)spring-servlet.xml
如果你有沒有在web.xml利用ContextLoaderListener來載入的spring configuration,SpringMVC則會自動載入/WEB-INF/spring-servlet.xml,如果沒用ContextLoaderListener也找不到該檔就會顯示錯誤

<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemalocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context-3.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns="http://www.springframework.org/schema/beans">

 <context:component-scan base-package="idv.elliot.web.controller"/>

 <bean class="org.springframework.web.servlet.view.UrlBasedViewResolver" id="viewResolver">
  <property name="viewClass" value="org.springframework.web.servlet.view.JstlView">
  </property><property name="prefix" value="/WEB-INF/jsp/">
  </property><property name="suffix" value=".jsp">
 </property></bean>
</beans> 

簡單來說,利用component-scan來找出利用annotation標示的Spring components,當中也包含了皆下來要提的Controller,然後建立一個viewResolver,這是用最基本的UrlBasedViewResolver
如此一來,當Controller的method回傳abc時,SpringMVC就會將其導向http://host/module/WEB-INF/jsp/abc.jsp
至於為什麼要把jsp放到/WEB-INF/下,則是因為這只要/WEB-INF/裡的所有東西必需是自系統內的servlet forward過去才能取得,一般人無法直接以url接觸到該resource

(4)建立Controller
先用個helloworld吧,Struts用Action,SpringMVC則是用Controller,
而要把Class當SpringMVC的Controller只要在Class前加上@Controller的annotation即可
基本的method則是return ModelAndView,然後在method前加上@RequestMapping的Annotation
下列這個Class說明當使用者輸入http://host/module/sayHello.do時即會呼叫HelloController.sayHello(),而回傳ModelAndView("hello")則是讓SpringMVC的ViewReslover找到對應的jsp。

package idv.elliot.web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
 
 @RequestMapping("/sayHello")
 public ModelAndView sayHello() {
  return new ModelAndView("hello");
 }
}

(5)hello.jsp
重點是jsp存放的位置,而不是jsp,請記得之前viewResolver的設定,要放在/WEB-INF/jsp/下即可

只要輸入http://host/module/sayHello.do就可以看到結果,而所有專案資料的截圖如下


12 4月 2010

StrutsSpringTestCase

Struts2的Unit Test說容易也是真的不麻煩,但如果希望測試得仔細些又要頗費力氣,還好在2.1.8時將一直沒有Commit到release repository的StrutsSpringTestCase放了出來,使Unit Test又更加方便。 下列寫個簡單例子:

public class FirstActionTest extends StrutsSpringTestCase{
	 public void testAction() throws Exception {  
		  ActionProxy actionProxy  = this.getActionProxy ( "first!index.action");  
		  Assert.assertNotNull(actionProxy);  
		  FirstAction action = (FirstAction) actionProxy.getAction();  
		  Assert.assertNotNull(action);  

		 String result = actionProxy.execute();  
		  Assert.assertEquals(FirstAction.SUCCESS , result);  
	 }  
} 
ActionProxy actionProxy  =  this.getActionProxy("first!index.action");
FirstAction action = (FirstAction) actionProxy.getAction();
String result = actionProxy.execute();
this.getActionProxy()內帶入你實際在跑的uri,取得Action後再設定你要測的property,最後再run actionProxy.execute();就可以做成一個簡單的測試,如果需要改變Spring configuration xml的位置,請override protected String getContextLocations(); 另外有兩點要注意,如果你使用wildcard如first_*來控制action的execution methed,請在測試時用!來分隔wildcard,trace了一段時間,還沒找出問題在哪...另一個是actionProxy.execute()會有找不到jsp的實際檔案的情形,但不影響測試,這部份應該是放到integration test就能解決。


Spring3與JPA2 (1)

ORM的選擇很多,雖然JEE訂出了一個規格JPA,但之前並不喜歡使用,主要是因為相較其他原生的library像Hibernate, Eclipse Link等,JPA在實際開發上並不如其他Library來得方便,沒有像Hibernate的Criteria這類API就令我很感冒,所以在ORM的Demo裡一直沒有把JPA納入,多半使用的都還是Hibernate。
直到JPA2規格訂完,Hibernate也出了Stable的版本,想想也該納入看一看了。Hibernate與JPA所訂的EntityManager差異還不小,從中轉換還是要看一下JPA2的Spec,但我發現花較多時間的是在Spring的Configuration,要設定的部份較原來的純Hibernate要多出不少,而且有些我看了還是有些疑惑,看來單單有關Configuration就要寫上幾篇筆記了。
下列是基本的Spring Configurations:
applicationContext.xml:

<? xml   version= "1.0"   encoding= "UTF-8" ?>
< beans   xmlns = "http://www.springframework.org/schema/beans" 
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns:context = "http://www.springframework.org/schema/context" 
   xmlns:util = "http://www.springframework.org/schema/util"  xmlns:p = "http://www.springframework.org/schema/p" 
   xmlns:tx = "http://www.springframework.org/schema/tx"  xmlns:aop = "http://www.springframework.org/schema/aop" 
   xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/tx   http://www.springframework.org/schema/tx/spring-tx.xsd 
       http://www.springframework.org/schema/aop   http://www.springframework.org/schema/aop/spring-aop.xsd 
       http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd ">  
  
   < context:property-placeholder   location = "classpath:system.properties"  />  
  
   < bean   id = "dataSource"  class = "com.mchange.v2.c3p0.ComboPooledDataSource">  
    < property   name = "driverClass"  value = "${jdbc.driverClass}"  />  
    < property   name = "jdbcUrl"  value = "${jdbc.url}"  />  
    < property   name = "user"  value = "${jdbc.user}"  />  
    < property   name = "password"  value = "${jdbc.password}"  />  
    < property   name = "autoCommitOnClose"  value = "${jdbc.autoCommitOnClose}"  />  
   </ bean>  
   
   < bean   id = "entityManagerFactory" 
    class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">  
    < property   name = "persistenceXmlLocation"  value = "org/elliot/dao/jpaimpl/persistence.xml"  />  
    < property   name = "dataSource"  ref = "dataSource"  />  
    < property   name = "jpaVendorAdapter">  
     < bean   class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">  
      < property   name = "database"  value = "${hibernate.database}"  />  
      < property   name = "showSql"  value = "${hibernate.show_sql}"  />  
      < property   name = "generateDdl"  value = "${hibernate.generate_ddl}"  />  
     </ bean>  
    </ property>  
    < property   name = "jpaPropertyMap">  
     < props>  
     < prop   key ="hibernate.cache.provider_class" > org.hibernate.cache.HashtableCacheProvider</ prop >  
     </ props>  
    </ property>  
   </ bean>  
  
   < bean   id = "entityManager" 
    class = "org.springframework.orm.jpa.support.SharedEntityManagerBean">  
    < property   name = "entityManagerFactory"  ref = "entityManagerFactory"  />  
   </ bean>  
  
   < bean   id = "transactionManager"  class = "org.springframework.orm.jpa.JpaTransactionManager">  
    < property   name = "entityManagerFactory"  ref = "entityManagerFactory"  />  
    < property   name = "dataSource"  ref = "dataSource"  />  
   </ bean>  
  
   < tx:annotation-driven  transaction-manager = "transactionManager"  
    proxy-target-class= "true"   />  
  
   < context:annotation-config  />  
   < context:component-scan   base-package = "org.elliot.dao.jpaimpl,org.elliot.service"  />  
  
</ beans> 

persistence.xml

< persistence   xmlns = "http://java.sun.com/xml/ns/persistence"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation = "http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" 
   version= "2.0" >  
   
   < persistence-unit   name = "Master"  transaction-type = "RESOURCE_LOCAL">  
   < class > org.elliot.domain.Master</ class >  
    < exclude-unlisted-classes/>  
   </ persistence-unit>  
  
</ persistence>

system.properties:

#h2database configurations
jdbc.driverClass= org.h2.Driver  
jdbc.url = jdbc:h2:~/test 
#jdbc.url=jdbc:h2:tcp://localhost/~/test 
jdbc.user= sa  
jdbc.password=  
jdbc.autoCommitOnClose= true  
  
hibernate.database= H2  
hibernate.dialect = org.hibernate.dialect.H2Dialect 
hibernate.show_sql= true  
hibernate.format_sql= true  
hibernate.generate_statistics= true  
hibernate.hbm2ddl.auto= create  
hibernate.cache.use_second_level_cache= true  
hibernate.generate_ddl= true

其中要注意的是Spring: entityManagerFactory的persistenceXmlLocation,基本上應是要指到META-INF下,這裡只是方便測試才搬出來,如果希望在其他不用Spring的案子使用要記得放回去,至於其他Spring還有許多相關的Configuration如loadTimeWeaver之類的就還在研究了。。。

12 8月 2009

Spring3 Maven Repository

Spring repositories
由於Spring3還是在測試階段,所以並沒有把library放到多數公開的repository上,所以要取用的話必需加些repository到maven裡

<repositories>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - External Bundle Milestones</id>
        <url>http://repository.springsource.com/maven/bundles/milestone</url>
    </repository>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - SpringSource Bundle Releases</id>
        <url>http://repository.springsource.com/maven/bundles/release</url>
    </repository>
    <repository>
        <id>SpringSource Enterprise Bundle Repository - External Bundle Releases</id>
        <url>http://repository.springsource.com/maven/bundles/external</url>
    </repository>
</repositories>

如果不知道有哪些library可以用,那可以透過下面這url確認一下

http://s3browse.com/explore/repository.springsource.com/maven/bundles/milestone/org/springframework/