在Spring Security4.0 中配置自定義的login頁面
最近在研究用Web應用,Security 部分無疑是重要的一塊。於是按照書上(《Spring in Action 第三版》)的說明自己配製了一個小例子試一下。
系統的自帶login頁面這塊很快調通了,可是自定義login頁面這塊卻遇上很大的問題,按照書上的配製,系統總是報錯:
"405 Request method'POST' not supported 。"
看來Spring security 4.0和之前的版本配製改變很多呀。
在網上找了許多BLOGS,都指向CSRF配置,於是修改了各種CSRF配置方式,但是都沒有任何效果。在這裡耽誤了兩天的時間,折騰得我快失去耐心了。
按照其他文章的步驟反覆重建工程,最後發現是login頁面的form標籤中的action路徑有問題,改為下面這樣,就可以工作了。
<formaction="${pageContext.request.contextPath}/login"method="post"class="form-horizontal">
之後又遇到CSS檔案無法載入問題,在沒有啟動Security時明明可以正常載入生效,但是啟動了Security之後就不生效,而且login頁面提交不成功。經過反覆測試,原來是
Security.xml檔案中少了一段如下程式碼,限制了對css檔案的訪問許可權,導致問題。
<httppattern="/resources/**"security="none"/>
<!-- 其他圖片資料夾 -->
<http pattern="/**/*.png"security="none"/>
<http pattern="/**/*.jpg"security="none"/>
<http pattern="/**/*.gif"security="none"/>
<http pattern="/**/*.htm*"security="none"/>
<!--
<http pattern="/**/*.css" security="none"/>
最終這個小程式除錯通過了,自定義的login頁面正常工作了,在此基礎上可以新增更完整的功能配置。想起為了這些基本的配置而耽誤的時間和遇到困難時的挫折,
我想把這個小例子分享在網上,以幫助想要使用Springsecurity 4.0的朋友們。如果能節約大家一點時間,那就值得了。
下面一步步介紹一下這個工程的各個部分:
首先來看工程架構:
這是一個在Eclipse中建立的Maven 工程,名稱Doctor,型別選擇maven-archetype-webapp。不同版本建立的目錄結構與檔案稍有不同,請調整。
以下是幾個關鍵性檔案,直接拷過來.....
1. pom.xml
既然使用maven,pom.xml必不可少:
<projectxmlns="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.0http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Private</groupId>
<artifactId>Doctor</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Doctor Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>4.0.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>Doctor</finalName>
</build>
</project>
2. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-appxmlns: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_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Archetype Created WebApplication</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 應用上下文配置檔案 -->
<param-value>/WEB-INF/dispatcher-servlet.xml,/WEB-INF/doctor-security.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- spring security start -->
<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>
<!-- spring security end -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3. dispatcher-servlet.xml
注意其中的mvc:resources配置必不可少,否則css和其他資原始檔無法訪問
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<context:component-scan base-package="com.doctor"/>
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**"location="/resources/" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
4. doctor-security.xml
<?xmlversion="1.0" encoding="UTF-8"?>
<b:beansxmlns="http://www.springframework.org/schema/security"
xmlns:b="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/securityhttp://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http pattern="/resources/**"security="none"/>
<!-- 其他圖片資料夾 -->
<http pattern="/**/*.png"security="none"/>
<http pattern="/**/*.jpg"security="none"/>
<http pattern="/**/*.gif"security="none"/>
<http pattern="/**/*.htm*"security="none"/>
<!-- 其他css -->
<http pattern="/**/*.css"security="none"/>
<!-- 所有的JS -->
<http pattern="/**/*.js"security="none"/>
<!-- 所有的flash -->
<http pattern="/**/*.swf"security="none"/>
<http auto-config="false"use-expressions="true">
<logout/>
<intercept-urlpattern="/login" access="permitAll" />
<!-- 允許訪問的uri -->
<intercept-urlpattern="/**" access="hasRole('ROLE_USER')" />
<!-- 登陸頁面配置 -->
<form-loginlogin-page="/login"
authentication-failure-url="/login?login_error=1"/>
<csrf />
</http>
<!-- 許可權管理者 -->
<authentication-manager>
<!-- 許可權提供者 -->
<authentication-provider>
<!-- 可提供登陸訪問的使用者 -->
<user-service>
<user name="Miler"password="Miler" authorities="ROLE_USER, ROLE_ADMIN" />
<user name="Johnson"password="Johnson" authorities="ROLE_USER" />
</user-service>
<!-- <jdbc-user-serviceid="userService"
data-source-ref="dataSource"
users-by-username-query=
'select user_name, password, enabled from"CFETEST"."USERS" where user_name=?'
authorities-by-username-query=
'select user_name, authority from"CFETEST"."USERS" where user_name=?'
/> -->
</authentication-provider>
</authentication-manager>
</b:beans>
5. HelloWorldController.java
package com.doctor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.DispatcherServlet;
@Controller
public class HelloWorldController {
@RequestMapping("/hello")
publicModelAndView helloWorld(){
Stringmessage = "你好,Programmer";
try{
//message=URLEncoder.encode(newString("你好 Programmer"),"utf-8");
}
catch(Exceptione)
{}
System.out.println(message);
returnnew ModelAndView("hellopage","message",message);
}
@RequestMapping(value= "/login", method = RequestMethod.GET)
public StringloginPage() {
return"login";
}
@RequestMapping(value= "/welcome", method = RequestMethod.GET)
public Stringwelcome() {
return"welcome";
}
}
6. index.jsp
<html>
<body>
<h2>HelloBoy!</h2>
<ahref="hello">please Click Here</a>
</body>
</html>
7. hellopage.jsp
<%@page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=UTF-8">
<link href="<%=basePath%>resources/css/app.css" rel="stylesheet" type="text/css"/>
<title>Insert titlehere</title>
</head>
<body>
Message:${message}
</body>
</html>
8. login.jsp
這個可是重點呀。
<%@page language="java" contentType="text/html;charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form"uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<metahttp-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
<title>Login page</title>
<link rel="stylesheet" type="text/css"href="${pageContext.request.contextPath}/resources/css/bootstrap.css"/>
<link rel="stylesheet"type="text/css"href="${pageContext.request.contextPath}/resources/css/app.css"/>
<link rel="stylesheet"type="text/css"href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/css/font-awesome.css"/>
</head>
<body>
<div id="mainWrapper">
<divclass="login-container">
<divclass="login-card">
<divclass="login-form">
<c:urlvar="loginUrl" value="/login" />
<form action="${pageContext.request.contextPath}/login" method="post" class="form-horizontal">
<c:iftest="${param.error != null}">
<divclass="alert alert-danger">
<p>Invalid username and password.</p>
</div>
</c:if>
<c:iftest="${param.logout != null}">
<divclass="alert alert-success">
<p>You have been logged out successfully.</p>
</div>
</c:if>
<divclass="input-group input-sm">
<labelclass="input-group-addon" for="username"><iclass="fa fa-user"></i></label>
<inputtype="text" class="form-control" id="username"name="username" placeholder="Enter Username" required>
</div>
<divclass="input-group input-sm">
<labelclass="input-group-addon" for="password"><iclass="fa fa-lock"></i></label>
<inputtype="password" class="form-control"id="password" name="password" placeholder="EnterPassword" required>
</div>
<inputtype="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<divclass="form-actions">
<input type="submit"
class="btn btn-block btn-primary btn-default" value="Login">
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
兩個CSS檔案如果需要,也請從那裡下載吧。