第六章、SpringBoot集成SpringSecurity

本文介绍了如何在SpringBoot项目中集成SpringSecurity进行权限管理。通过配置文件、安全配置类和控制器,实现了用户登录、权限验证、登出等功能。在header.html中,根据用户登录状态动态展示菜单,未登录时显示登录按钮,登录后显示用户名和退出选项。用户列表页面受到保护,未登录用户会被重定向到登录页面。
摘要由CSDN通过智能技术生成

下面是一个简单的登录测试案例

项目结构大致如下,里面部分内容与上一篇博客相同

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")//需要相应的角色才能访
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

荒--

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值