Code ví dụ Spring Security, Tạo form login – XML Config
Các công nghệ sử dụng:
- Spring 5.0.2.RELEASE
- Spring Security 5.0.2.RELEASE
- Maven
- Tomcat
- JDK 1.8
- Eclipse + Spring Tool Suite
Code ví dụ Spring MVC Security: Tạo, đăng ký form login tùy chỉnh – XML Config. Hướng dẫn cấu hình config ví dụ Spring MVC Security Form Login
Tạo Maven Project
Thư viện sử dụng:
Ở đây mình sử dụng Spring Security 5.0.2.RELEASE
<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>stackjava.com</groupId>
<artifactId>SpringMvcSecurityHello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>5.0.2.RELEASE</spring.version>
<spring.security.version>5.0.2.RELEASE</spring.security.version>
<jstl.version>1.2</jstl.version>
</properties>
<dependencies>
<!-- Spring MVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jstl for jsp page -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
</dependencies>
</project>
File web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>SpringSecurityFormLogin</display-name>
<!-- SPRING MVC -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- Loads Spring Security config file -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<!-- Spring Security -->
<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>
</web-app>
File Spring Config:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
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-4.3.xsd">
<context:component-scan base-package="stackjava.com.springsecurityformlogin" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
File Spring Security Config:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/admin**" access="hasRole('ROLE_ADMIN')" />
<form-login
login-page="/login"
login-processing-url="/j_spring_security_login"
default-target-url="/admin"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<logout logout-url="/j_spring_security_logout"
logout-success-url="/logout" delete-cookies="JSESSIONID" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="{noop}123456" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
Để đăng ký form login ta sử dụng thẻ <form-login>
Một số thuộc tính của thẻ <form-login> gồm:
- always-use-default-target Nếu bằng
truethì sẽ luôn chuyển hướng người dùng tới URL được định nghĩa ở thuộc tính default-target-url, bất kể hành động trước đó của người dùng muốn truy cập vào URL nào. Giá trị mặc định làfalse. - authentication-failure-url Định nghĩ URL sẽ được chuyển hướng tới nếu login thất bại, Mặc định là
/login?error -
authentication-failure-handler-ref Có thể sử dụng thay thế thuộc tính authentication-failure-url, nó cho phép bạn điều khiển luồng sau khi xác thực thất bại.
- default-target-url Định nghĩa URL mặc định được chuyển hướng tới sau khi login thành công.
- authentication-success-handler-ref Có thể sử dụng để thay thế thuộc tính default-target-url và always-use-default-target, Cho phép điều khiển luồng, bổ sung hành động sau khi xác thực thành công.
- login-page URL được sử dụng để render trang login, mặc định là “/login”.
- login-processing-url URL mà Spring Security xử lý hành động login. mặc định là “/login”. Trong ví dụ này mình để là “
/j_spring_security_login” thì action trong form login cũng sẽ có giá trị là “/j_spring_security_login“ - password-parameter Tên của request parameter chứa password, mặc định là “password”.
- username-parameter Tên của request parameter chứa username, mặc định là “username”
File Controller:
package stackjava.com.springsecurityformlogin.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class BaseController {
@RequestMapping(value = { "/login", "/" })
public String login(@RequestParam(value = "error", required = false) final String error,
final Model model) {
if (error != null) {
model.addAttribute("message", "Login Failed!");
}
return "login";
}
@RequestMapping("/admin")
public String admin() {
return "admin";
}
@RequestMapping("/logout")
public String logout(final Model model) {
model.addAttribute("message", "Logged out!");
return "login";
}
}
File view:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>login</title>
</head>
<body>
<h1>Spring MVC-Security Login Form</h1>
<h2>${message}</h2>
<form name='loginForm' action="<c:url value='j_spring_security_login' />" method='POST'>
<table>
<tr>
<td>User:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password' /></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="login" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
</body>
</html>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Admin Page</title>
</head>
<body>
<h1>Admin Page</h1>
<h2>Welcome: ${pageContext.request.userPrincipal.name}</h2>
<form action="<c:url value="/j_spring_security_logout" />" method="post">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<input type="submit" value="Logout" />
</form>
</body>
</html>
Demo:
Trường hợp login thất bại.
Trường hợp login thành công.
Trường hợp logout.
Code ví dụ Spring Security, Tạo form login – XML Config
Okay, Done!
Download code ví dụ trên tại đây.
References:
https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#nsa-form-login




