今天我们将在上一篇博客《Spring Boot(四):Spring Boot 集成 Thymeleaf》的基础上来集成Spring Security.
1. 添加Maven依赖
在pom.xml引用spring security.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
添加Maven依赖后,运行项目,访问https://localhost:8443/SpringBootBase/ 浏览器会弹出如下身份验证框:
如图1所示:
这是因为Spring Security对我们的工程默认使用"basic"身份认证,只要引入了Spring Security, 那么整个web应用都是安全的,所有资源访问都要经过身份验证授权才可以访问。可用user 及 随机密码登录,随机密码可从web应用启动日志查询, 如:
Using default security password: 89c19869-277c-4eba-89c8-590e0405ae84
当然也可以在application.properties里自定义username和password.
security.user.name=admin
security.user.password=123456
或者直接关闭这个默认的basic认证
security.basic.enabled=false
详情请参考官方文档:https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/html/boot-features-security.html
当你客制化自己的授权体系后,这个默认的"basic"认证将会自动被替代。
2. 配置spring security
我们还是以上一篇博客的工程代码为基础来整合Spring Security.
- index.html: 登录界面
<!DOCTYPE html>
<html lang="zh-cn" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>Login</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}"/>
<link rel="stylesheet" th:href="@{css/customer/login.css}"/>
</head>
<body>
<div class="container">
<h3 align="center">这是一个带有登录框的主页</h3>