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>

 

 

Spring Security OAuth2 Authorization Server 是一个基于 Spring Security 的 OAuth2 认证服务器,用于管理 OAuth2 模式下的授权和令牌。 要将 Spring BootSpring Security OAuth2 Authorization Server 集成,可以遵循以下步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-authorization-server</artifactId> <version>0.2.1</version> </dependency> ``` 2. 配置认证服务器 创建一个配置类,用于配置 OAuth2 认证服务器。这个类需要继承 AuthorizationServerConfigurerAdapter 类,并且实现 configure 方法。 ```java @Configuration public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // 配置客户端信息 clients.inMemory() .withClient("client") .secret("{noop}secret") .authorizedGrantTypes("authorization_code", "refresh_token") .redirectUris("http://localhost:8080/client") .scopes("read", "write"); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { // 配置安全性 security.checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // 配置端点 endpoints.authenticationManager(authenticationManager); } } ``` 上面的代码中,我们配置了一个名为 "client" 的客户端,使用了授权码模式和刷新令牌模式。授权成功后,将重定向到 "http://localhost:8080/client" 页面。 3. 配置 Spring Security 为了使 OAuth2 认证服务器正常工作,需要配置 Spring Security。可以创建一个配置类,用于配置 Spring Security。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 配置 HTTP 安全性 http.authorizeRequests() .antMatchers("/oauth2/authorize").authenticated() .and().formLogin().and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置身份认证管理器 auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } } ``` 在上面的代码中,我们配置了 HTTP 安全性和身份认证管理器。只有经过身份认证的用户才能访问 "/oauth2/authorize" 端点。 4. 启动应用程序 现在可以启动应用程序,并访问 "http://localhost:8080/oauth2/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8080/client" 来进行授权。授权成功后,将重定向到 "http://localhost:8080/client" 页面。 以上就是整合 Spring BootSpring Security OAuth2 Authorization Server 的基本步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值