下面是一个简单的登录测试案例
项目结构大致如下,里面部分内容与上一篇博客相同
pom.xml需要添加两个jar包
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--对Thymeleaf添加Spring Security标签支持-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.2.RELEASE</version>
</dependency>
配置文件application.properties 如下
#### thymeleaf配置 #######
spring.thymeleaf.mode=HTML5
# 编码
spring.thymeleaf.encoding=UTF-8
# 类型
spring.thymeleaf.content-type=text/html
# 开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
# 默认路径
spring.thymeleaf.prefix=classpath:/templates/
# 后缀
spring.thymeleaf.suffix=.html
# 启用MVC Thymeleaf视图分辨率
spring.thymeleaf.enabled=true
#使用H2 控制台
spring.h2.console.enabled=true
#MySQL数据库
# 服务器端口,如果不配置默认是8080端口
server.port=8080
# 数据库设置
spring.datasource.url=jdbc:mysql://localhost:3306/blog?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#JPA
#控制台输出格式化的sql
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format-sql=true
#每次程序结束的时候会清空表
spring.jpa.hibernate.ddl-auto=create-drop
SpringScurity配置类SecurityConfig如下
package com.waylau.spring.boot.blog.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
/**
* 安全配置类
*/
@EnableWebSecurity//启用web安全
public class SecurityConfig extends WebSecurityConfigurerAdapter{
/**
* 自定义配置
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/css/**", "/js/**", "/fonts/**", "/index").permitAll()//都可以访问
.antMatchers("/users/**").hasRole("ADMIN")//需要相应的角色才能访