最近在研究用spring mvc 4.0开发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"/>
<!-- 其他css -->
<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>
最后,本文的一些配置来源于这个Blog, http://websystique.com/spring-security/spring-security-4-custom-login-form-annotation-example/.
两个CSS文件如果需要,也请从那里下载吧。