SpringBoot整合Spring-Security

本文介绍如何在Spring Boot项目中集成Spring Security进行权限管理,并使用Thymeleaf作为模板引擎展示受保护的内容。文章详细展示了依赖添加、安全配置类编写及页面授权展示的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、添加依赖

// 添加spring security依赖
	compile('org.springframework.boot:spring-boot-starter-security')
	// 添加Thymeleaf spring security依赖
	compile('org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE')

2、集成接口WebSecurityConfigurerAdapter

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;

/**
 * 安全配之类
 * @author Administrator
 *
 */
@EnableWebSecurity
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") // 需要相应的角色才能访问
			.and()
			.formLogin() // 基于表单Form登录验证
			.loginPage("/login").failureUrl("/login-error");//自定义登录界面
	}
	
	/**
	 * 认证管理信息
	 * @param auth
	 * @throws Exception
	 */
	@Autowired
	public void configureGlobal(AuthenticationManagerBuilder auth)throws Exception{
		auth.inMemoryAuthentication() // 认证信息存储于内存中
			.withUser("waylau").password("123456").roles("ADMIN");
	}
}

3、页面运用

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8">
<title>Thymeleaf in action</title>
</head>
<body>
	<div th:replace="~{fragments/header :: header}"></div>
<!-- Page Content -->
<div class="container blog-content-container">

    <div sec:authorize="isAuthenticated()">
    	<p>已有用户登录</p>
    	<p>登录的用户为:<span sec:authentication="name"></span> </p>
    	<p>用户角色为:<span sec:authentication="principal.authorities"></span> </p>
    </div>
	<div sec:authorize="isAnonymous()">
		<p>未有用户登录</p>
	</div>

</div>
<!-- /.container -->


<div th:replace="~{fragments/footer :: footer}">...</div>
</body>
</html>

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值