Spring Security笔记:自定义登录页

以下内容参考了 http://www.mkyong.com/spring-security/spring-security-form-login-example/

接上回,在前面的Hello World示例中,Spring Security为我们自动生成了默认登录页,对于大多数项目而言,如此简单的登录页并不能满足实际需求,接下来,我们看看如何自定义登录页

一、项目结构

Spring Security笔记:自定义登录页

前一个示例相比较,只是多了一个css样式以及登录页login.jsp,这二个文件具体的内容如下:

 @CHARSET "UTF-8";

 .error {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
} .msg {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
} #login-box {
width: 300px;
padding: 20px;
margin: 100px auto;
background: #fff;
-webkit-border-radius: 2px;
-moz-border-radius: 2px;
border: 1px solid #000;
}

login.css

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<link rel="Stylesheet" type="text/css" href="${pageContext.request.contextPath}/resources/css/login.css" />
</head>
<body onload='document.loginForm.username.focus();'>
<h1>Spring Security Custom Login Form (XML)</h1> <div id="login-box">
<h3>Login with Username and Password</h3>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
<form name='loginForm'
action="<c:url value='j_spring_security_check' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username' value=''></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"
value="submit" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
</div>
</body>
</html>

login.jsp

有几个地方解释一下:

第9行,css静态资源的引用方式,如果对Spring MVC不熟悉的人,可借此示例学习一下

15-20行,用了一个if标签来判断登录验证是否有错,如果验证失败,则显示错误信息,其中error,msg这二个变量,是从Controller里返回的信息(后面马上会讲到)

23行form表单的action地址留意一下,这个不能改,这是Spring Security的约定

38-39行的隐藏域_csrf,这是用来防止跨站提交攻击的,如果看不懂,可暂时无视。

二、Controller

 package com.cnblogs.yjmyzz;

 import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; @Controller
public class HelloController { @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public ModelAndView welcome() { ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Custom Login Form");
model.addObject("message", "This is welcome page!");
model.setViewName("hello");
return model; } @RequestMapping(value = "/admin", method = RequestMethod.GET)
public ModelAndView admin() { ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Custom Login Form");
model.addObject("message", "This is protected page!");
model.setViewName("admin"); return model; } //新增加的Action方法,映射到
// 1. /login 登录页面的常规显示
// 2. /login?error 登录验证失败的展示
// 3. /login?logout 注销登录的处理
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(
@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) { ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
} if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login"); return model; } }

HelloController

增加了一个login方法,映射到登录的三种情况(常规显示,出错展示,注销登录)

三、spring-security.xml

 <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-3.2.xsd"> <http auto-config="true">
<intercept-url pattern="/admin" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/login?error" username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout" />
<!-- enable csrf protection -->
<csrf />
</http> <authentication-manager>
<authentication-provider>
<user-service>
<user name="yjmyzz" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager> </beans:beans>

spring-security.xml

注意8-16行的变化,一看即懂,就不多做解释了

运行效果:

登录页正常显示的截图

Spring Security笔记:自定义登录页

登录失败的截图

Spring Security笔记:自定义登录页

有兴趣的还可以看下对应的html源代码

Spring Security笔记:自定义登录页

防跨站提交攻击的_csrf隐藏域,会生成一个随机的类似guid字符串来做校验,以确定本次http post确实是从本页面发起的,这跟asp.net里mac ViewState的思路一致。

最后附示例源代码下载:SpringSecurity-CustomLoginForm-XML(0717).zip

上一篇:CAS—改动默认登录页


下一篇:python爬虫scrapy框架——人工识别知乎登录知乎倒立文字验证码和数字英文验证码