默认情况下,如果未指定登录表单,Spring Security将自动创建一个默认登录表单。 请参考这个– Spring Security hello world示例 。
在本教程中,我们将向您展示如何为Spring Security(XML示例)创建自定义登录表单。
使用的技术:
- 春天3.2.8。发布
- Spring Security 3.2.3发布
- Eclipse 4.2
- JDK 1.6
- Maven 3
注意
在此示例中,将重用先前的Spring Security hello world示例 ,对其进行增强以支持自定义登录表单。
1.项目演示
2.目录结构
查看本教程的最终目录结构。
3. Spring安全配置
在Spring XML文件中定义了您的自定义登录表单。 请参阅以下说明:
- login-page =” / login” –显示自定义登录表单的页面
- authentication-failure-url =” / login?error” –如果身份验证失败,则转发到页面
/login?error
- logout-success-url =” / login?logout” –如果注销成功,请前进以查看
/logout
- username-parameter =“用户名” –包含“用户名”的请求的名称。 在HTML中,这是输入文本的名称。
- <csrf /> –启用跨站点请求伪造(CSRF)保护,请参阅此链接 。 在XML中,默认情况下禁用CSRF保护。
通常,我们不参与登录或注销处理之类的身份验证,让Spring处理它,我们只处理要显示的成功或失败页面。
<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="mkyong" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
在上面的祝贺中, /admin
及其子文件夹均受密码保护。
跨站请求伪造(CSRF)保护
如果启用了CSRF,则必须在要登录或注销的页面中包含_csrf.token
。 请参阅下面的login.jsp
和admin.jsp
(注销表单)。 否则,登录和注销功能都将失败。
明文密码?
一个非常糟糕的主意,您应该始终使用SHA算法对密码进行哈希处理,本教程向您展示-Spring Security密码哈希处理示例。
4.自定义登录表格
一个与上述内容匹配的自定义登录表单(步骤3),祝贺Spring Security。 它应该是不言自明的。
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.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;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>
<h1>Spring Security Custom Login Form (XML)</h1>
<div id="login-box">
<h2>Login with Username and Password</h2>
<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>
另外两个JSP页面btw admin.jsp
受Spring Security密码保护。
<%@page session="false"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
</body>
</html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
<c:url value="/j_spring_security_logout" var="logoutUrl" />
<!-- csrt for log out-->
<form action="${logoutUrl}" method="post" id="logoutForm">
<input type="hidden"
name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>
<script>
function formSubmit() {
document.getElementById("logoutForm").submit();
}
</script>
<c:if test="${pageContext.request.userPrincipal.name != null}">
<h2>
Welcome : ${pageContext.request.userPrincipal.name} | <a
href="javascript:formSubmit()"> Logout</a>
</h2>
</c:if>
</body>
</html>
5. Spring MVC控制器
一个简单的控制器。
package com.mkyong.web.controller;
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 welcomePage() {
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 adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Custom Login Form");
model.addObject("message", "This is protected page!");
model.setViewName("admin");
return model;
}
//Spring Security see this :
@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;
}
}
6.演示
6.1。 欢迎页面-http:// localhost:8080 / spring-security-loginform-xml /
6.2尝试访问/admin
页面,Spring Security将拦截请求并重定向到/login
,并显示您的自定义登录表单。
6.3。 如果用户名和密码不正确,将显示错误消息,Spring将重定向到该URL /login?error
。
6.4。 如果用户名和密码正确,Spring将重定向到原始请求的URL并显示页面。
6.5。 尝试注销,它将重定向到/login?logout
页面。
下载源代码
下载它– spring-security-custom-login-form-xml.zip (15 KB)
参考文献
翻译自: https://mkyong.com/spring-security/spring-security-form-login-example/