SpringBoot与SpringSecurity整合方法附源码

 更新时间:2021年1月26日 19:46  点击:1947

依赖

<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<!-- Thymeleaf -->
	<dependency>
		<groupId>org.thymeleaf</groupId>
		<artifactId>thymeleaf-spring5</artifactId>
	</dependency>
	<dependency>
		<groupId>org.thymeleaf.extras</groupId>
		<artifactId>thymeleaf-extras-java8time</artifactId>
	</dependency>
	<!-- SpringSecurity -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-security</artifactId>
	</dependency>
	<!-- Thymeleaf 与 SpringSecurity 整合包 -->
	<dependency>
 		<groupId>org.thymeleaf.extras</groupId>
 		<artifactId>thymeleaf-extras-springsecurity5</artifactId>
 		<version>3.0.4.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
		<exclusions>
			<exclusion>
				<groupId>org.junit.vintage</groupId>
				<artifactId>junit-vintage-engine</artifactId>
			</exclusion>
		</exclusions>
	</dependency>
</dependencies>

Controller:

package com.blu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouterController {

	@RequestMapping({ "/", "/index" })
	public String index() {
		return "index";
	}

	@RequestMapping("/tologin")
	public String toLogin() {
		return "views/login";
	}

	@RequestMapping("/level1/{id}")
	public String level1(@PathVariable("id") int id) {
		return "views/level1/" + id;
	}

	@RequestMapping("/level2/{id}")
	public String level2(@PathVariable("id") int id) {
		return "views/level2/" + id;
	}

	@RequestMapping("/level3/{id}")
	public String level3(@PathVariable("id") int id) {
		return "views/level3/" + id;
	}
	
}

SecurityConfig:

package com.blu.config;

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;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{
	
	/**
	 * 授权
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		//所有人可以访问首页,功能页需要指定权限才可以访问
		http.authorizeRequests()
			.antMatchers("/").permitAll()
			.antMatchers("/level1/**").hasRole("vip1")
			.antMatchers("/level2/**").hasRole("vip2")
			.antMatchers("/level3/**").hasRole("vip3");
		
		//没有权限将默认跳转至登录页,需要开启登录的页面
		//loginPage设置跳转至登录页的请求(默认为/login)
		//usernameParameter和passwordParameter配置登录的用户名和密码参数名称,默认就是username和password
		//loginProcessingUrl配置登录请求的url,需要和表单提交的url一致
		http.formLogin().loginPage("/tologin")
						.usernameParameter("username")
						.passwordParameter("password")
						.loginProcessingUrl("/login");
		//禁用CSRF保护
		http.csrf().disable();
		//开启注销功能和注销成功后的跳转页面(默认为登录页面)
		http.logout().logoutSuccessUrl("/");
		//开启记住我功能,Cookie默认保存两周
		http.rememberMe().rememberMeParameter("remember");
		
	}
	
	/**
	 * 认证
	 */
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		
		auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
			.withUser("BLU").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
			.and()
			.withUser("root").password(new BCryptPasswordEncoder().encode("111111")).roles("vip1","vip2","vip3")
			.and()
			.withUser("guest").password(new BCryptPasswordEncoder().encode("111222")).roles("vip1");
	}
	
}

注:以上方式认证的用户和角色信息是存储在内存中的,在实际开发中应该从数据库中获取,详见:SpringSecurity从数据库中获取用户信息进行验证

index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
 <title>首页</title>
 <!--semantic-ui-->
 <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet">
 <link th:href="@{/qinjiang/css/qinstyle.css}" rel="external nofollow" rel="external nofollow" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

 <div class="ui segment" id="index-header-nav" th:fragment="nav-menu">
  <div class="ui secondary menu">
   <a class="item" th:href="@{/index}" rel="external nofollow" >首页</a>

   <!--登录注销-->
   <div class="right menu">
    <!--如果未登录-->
 				<div sec:authorize="!isAuthenticated()">
  				<a class="item" th:href="@{/tologin}" rel="external nofollow" >
   				<i class="address card icon"></i> 登录
  				</a>
 				</div>
    <!--如果已登录-->
 				<div sec:authorize="isAuthenticated()">
  				<a class="item">
   				<i class="address card icon"></i>
   				用户名:<span sec:authentication="principal.username"></span>
   				角色:<span sec:authentication="principal.authorities"></span>
  				</a>
 				</div>
 				<div sec:authorize="isAuthenticated()">
  				<a class="item" th:href="@{/logout}" rel="external nofollow" >
   				<i class="address card icon"></i> 注销
  				</a>
 				</div>
   </div>
  </div>
 </div>

 <div class="ui segment" style="text-align: center">
  <h3>Spring Security Study by BLU</h3>
 </div>

 <div>
  <br>
  <div class="ui three column stackable grid">
   <div class="column" sec:authorize="hasRole('vip1')">
    <div class="ui raised segment">
     <div class="ui">
      <div class="content">
       <h5 class="content">Level 1</h5>
       <hr>
       <div><a th:href="@{/level1/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-1</a></div>
       <div><a th:href="@{/level1/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-2</a></div>
       <div><a th:href="@{/level1/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-1-3</a></div>
      </div>
     </div>
    </div>
   </div>

   <div class="column" sec:authorize="hasRole('vip2')">
    <div class="ui raised segment">
     <div class="ui">
      <div class="content">
       <h5 class="content">Level 2</h5>
       <hr>
       <div><a th:href="@{/level2/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-1</a></div>
       <div><a th:href="@{/level2/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-2</a></div>
       <div><a th:href="@{/level2/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-2-3</a></div>
      </div>
     </div>
    </div>
   </div>

   <div class="column" sec:authorize="hasRole('vip3')">
    <div class="ui raised segment">
     <div class="ui">
      <div class="content">
       <h5 class="content">Level 3</h5>
       <hr>
       <div><a th:href="@{/level3/1}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-1</a></div>
       <div><a th:href="@{/level3/2}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-2</a></div>
       <div><a th:href="@{/level3/3}" rel="external nofollow" ><i class="bullhorn icon"></i> Level-3-3</a></div>
      </div>
     </div>
    </div>
   </div>

  </div>
 </div>
 
</div>


<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>

views/login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
 <title>登录</title>
 <!--semantic-ui-->
 <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

 <div class="ui segment">

  <div style="text-align: center">
   <h1 class="header">登录</h1>
  </div>

  <div class="ui placeholder segment">
   <div class="ui column very relaxed stackable grid">
    <div class="column">
     <div class="ui form">
      <form th:action="@{/login}" method="post">
       <div class="field">
        <label>Username</label>
        <div class="ui left icon input">
         <input type="text" placeholder="Username" name="username">
         <i class="user icon"></i>
        </div>
       </div>
       <div class="field">
        <label>Password</label>
        <div class="ui left icon input">
         <input type="password" name="password">
         <i class="lock icon"></i>
        </div>
       </div>
       <div class="field">
       	<input type="checkbox" name="remember"> 记住我
       </div>
       
       <input type="submit" class="ui blue submit button"/>
      </form>
     </div>
    </div>
   </div>
  </div>

  <div style="text-align: center">
   <div class="ui label">
    </i>注册
   </div>
   <br><br>
   <small>736917155@qq.com</small>
  </div>
  <div class="ui segment" style="text-align: center">
   <h3>Spring Security Study by BLU</h3>
  </div>
 </div>


</div>

<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>

views/level1/1.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
 <title>首页</title>
 <!--semantic-ui-->
 <link href="https://cdn.bootcss.com/semantic-ui/2.4.1/semantic.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="stylesheet">
 <link th:href="@{/qinjiang/css/qinstyle.css}" rel="external nofollow" rel="external nofollow" rel="stylesheet">
</head>
<body>

<!--主容器-->
<div class="ui container">

 <div th:replace="~{index::nav-menu}"></div>

 <div class="ui segment" style="text-align: center">
  <h3>Level-1-1</h3>
 </div>

</div>

<script th:src="@{/qinjiang/js/jquery-3.1.1.min.js}"></script>
<script th:src="@{/qinjiang/js/semantic.min.js}"></script>

</body>
</html>

views/level2/1.html 等其他页面:略

运行效果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

项目源码:

链接: https://pan.baidu.com/s/1AtbcCht84NT-69-sSUAQRw

提取码: nh92

到此这篇关于SpringBoot与SpringSecurity整合的文章就介绍到这了,更多相关SpringBoot与SpringSecurity整合内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章

  • 解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题

    这篇文章主要介绍了解决springboot使用logback日志出现LOG_PATH_IS_UNDEFINED文件夹的问题,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-04-28
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • 详解springBoot启动时找不到或无法加载主类解决办法

    这篇文章主要介绍了详解springBoot启动时找不到或无法加载主类解决办法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • SpringBoot集成Redis实现消息队列的方法

    这篇文章主要介绍了SpringBoot集成Redis实现消息队列的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • 解决Springboot get请求是参数过长的情况

    这篇文章主要介绍了解决Springboot get请求是参数过长的情况,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-17
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • Spring Boot项目@RestController使用重定向redirect方式

    这篇文章主要介绍了Spring Boot项目@RestController使用重定向redirect方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-02
  • springBoot 项目排除数据库启动方式

    这篇文章主要介绍了springBoot 项目排除数据库启动方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-10
  • springboot中使用@Transactional注解事物不生效的坑

    这篇文章主要介绍了springboot中使用@Transactional注解事物不生效的原因,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-26
  • 详解SpringBoot之访问静态资源(webapp...)

    这篇文章主要介绍了详解SpringBoot之访问静态资源(webapp...),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-14
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • springboot多模块包扫描问题的解决方法

    这篇文章主要介绍了springboot多模块包扫描问题的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-09-16
  • Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用详解

    这篇文章主要介绍了Springboot mybatis plus druid多数据源解决方案 dynamic-datasource的使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-11-18
  • Springboot实现多线程注入bean的工具类操作

    这篇文章主要介绍了Springboot实现多线程注入bean的工具类操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-27
  • Springboot+MDC+traceId日志中打印唯一traceId

    本文主要介绍了Springboot+MDC+traceId日志中打印唯一traceId,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-10-17
  • SpringBoot部署到Linux读取resources下的文件及遇到的坑

    本文主要给大家介绍SpringBoot部署到Linux读取resources下的文件,在平时业务开发过程中,很多朋友在获取到文件内容乱码或者文件读取不到的问题,今天给大家分享小编遇到的坑及处理方案,感兴趣的朋友跟随小编一起看看吧...2021-06-21
  • 关于springboot中nacos动态路由的配置

    这篇文章主要介绍了springboot中nacos动态路由的配置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-11
  • SpringBoot高版本修改为低版本时测试类报错的解决方案

    这篇文章主要介绍了SpringBoot高版本修改为低版本时测试类报错的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-18
  • 解决Springboot整合shiro时静态资源被拦截的问题

    这篇文章主要介绍了解决Springboot整合shiro时静态资源被拦截的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-26
  • springboot配置多数据源后mybatis拦截器失效的解决

    这篇文章主要介绍了springboot配置多数据源后mybatis拦截器失效的解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-09-23