1. 程式人生 > >基於spring security的簡易使用者身份認定(基於xml)

基於spring security的簡易使用者身份認定(基於xml)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wyc</groupId>
  <artifactId>SpringSecurity</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringSecurity Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.10</version>
      <scope>test</scope>
    </dependency>
    <!-- http://mvnrepository.com/artifact/org.springframework/spring-core -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-core</artifactId>
	    <version>4.2.6.RELEASE</version>
	</dependency>
	<!-- http://mvnrepository.com/artifact/org.springframework/spring-context -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-context</artifactId>
	    <version>4.2.6.RELEASE</version>
	</dependency>
	<!-- http://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
	<dependency>
	    <groupId>org.springframework</groupId>
	    <artifactId>spring-webmvc</artifactId>
	    <version>4.2.6.RELEASE</version>
	</dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-web</artifactId>
        <version>4.1.0.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.1.0.RELEASE</version>
    </dependency>
    <dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>javax.servlet-api</artifactId>
	    <version>3.0.1</version>
	    <!-- 只在編譯和測試時執行 -->
	    <scope>provided</scope>
	</dependency>
  </dependencies>
  <build>
    <finalName>SpringSecurity</finalName>
     <plugins>
        <plugin>
            <groupId>org.apache.tomcat.maven</groupId>
	          <artifactId>tomcat7-maven-plugin</artifactId>
	          <version>2.2</version>
        </plugin>
    </plugins>
  </build>
</project>


web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  <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>
 <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
</web-app>

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
		<http auto-config="true">
		    <!-- 此處注意加上hasRole,否則報錯,同時單引號內容必須為大寫,下同,否則403錯誤 -->
		    <intercept-url pattern="/index.jsp" access="hasRole('USER')"/>
		</http>
		<authentication-manager>
		    <authentication-provider>
				<user-service>
				    <user name="tom" password="tom" authorities="ROLE_USER"/>
				    <user name="mike" password="mike" authorities="ROLE_ADMIN"/>
				</user-service>
		    </authentication-provider>
		</authentication-manager>
</beans:beans>


以上倆個檔案均存放在/WEB-INF目錄下

結果如下圖:

登入頁面(系統自帶)


使用tom登入


使用mike登入


當applicationContext.xml(即缺少hasRole)修改如下

<intercept-url pattern="/index.jsp" access="USER"/>
訪問時會出現如下錯誤:
java.lang.IllegalArgumentException: Failed to evaluate expression 'USER'

如果將applicationContext.xml改成如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/security
		http://www.springframework.org/schema/security/spring-security.xsd">
		
		<http use-expressions="false">
			<intercept-url pattern="/**" access="ROLE_USER" />
			<http-basic />
		</http>
		<authentication-manager>
		    <authentication-provider>
				<user-service>
				    <user name="tom" password="tom" authorities="ROLE_USER"/>
				    <user name="mike" password="mike" authorities="ROLE_ADMIN"/>
				</user-service>
		    </authentication-provider>
		</authentication-manager>
</beans:beans>

暫時不是很明白這樣配置的意義,spring security原文如下:

Basic authentication will then take precedence and will be used to prompt for a login when a user attempts to access a protected resource. Form login is still available in this configuration if you wish to use it, for example through a login form embedded in another web page.

結果如下:


若是使用自定義的登入頁面,applicationContext.xml修改如下:

<http use-expressions="true" auto-config="true">
		    <intercept-url pattern="/index.jsp" access="hasRole('USER')"/>
		    <form-login login-page="/login.jsp" login-processing-url="/check_action"
		        always-use-default-target="true"
		        default-target-url="/success.jsp"
		        username-parameter="username"
		        password-parameter="password"/>
		</http>


其中,login-page屬性指的是登入頁面,後倆個屬性則與登入頁面的form表單有關,登入頁面login.jsp 內的form表單如下:
<form method="post" action="<c:url value='check_action' />">
    	<input type="text" name="username">
    	<input type="password" name="password">
    	<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    	<input type="submit" value="提交">
    </form>

其中,action屬性與applicationContext.xml中的login-processing-url屬性的值必須相同,前倆個input的name屬性的值則對應配置檔案的username-parameter和password-parameter的值,第三個input是由於spring security使用了csrf(具體是什麼還沒有去了解),所以必須加入。

如果加入之後執行程式出現以下錯誤:

HTTP Status 403 - Could not verify the provided CSRF token because your session was not found in spring security。

則需要修改login.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"  isELIgnored="false"%>
加入最後一個屬性對,因為報這個錯的原因是form表單中的csrf未能解析(可以通過檢視原始碼發現此時csrf並沒有任何變化)