文章目录

  • SpringSecurity
    • 一、 概述
    • 二、SpringSecurity环境搭建
      • 1.配置template文件
      • 2.导入Pom.xml依赖
      • 3.配置RouterController层
      • 4.配置完测试
    • 三、 权限认证
      • 1.在pom.xml加入下面依赖
      • 2.配置config中 SecurityConfig
    • 四、用户注销和控制权限
      • 1.配置pom.xml
      • 2.配置RouteController
      • 3.权限控制
    • 四、remeberme和主页定制

SpringSecurity

一、 概述

我学习SpringSecurity大概分为四部分:

  • 配置SpringSecurity环境,
  • SpringSecurity认证
  • 用户注销和控制权限
  • RememberMe功能的实现

二、SpringSecurity环境搭建

最终目录大概如下

我们需要配置如下: template和static文件会在后面发

1.配置template文件

2.导入Pom.xml依赖

这里只需要导入web依赖和thymeleaf依赖就可以了

<!--        thymeleaf模板--><dependency><groupId>org.thymeleaf</groupId><artifactId>thymeleaf-spring5</artifactId></dependency><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-java8time</artifactId></dependency>
<!--      web--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

3.配置RouterController层

package com.kuang.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;}
//    这个level是随便写的只不过需要网页中的和这个对应@RequestMapping("/level3/{id}")public String level3(@PathVariable("id") int id){return "views/level3/"+id;}
}

4.配置完测试

输入网址: http://localhost:8080/ 可以跳转到正确页面,并且图各种vip1可以点击进去就可以了

三、 权限认证

1.在pom.xml加入下面依赖

<!--        配置SpringSecurity依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>

2.配置config中 SecurityConfig

首先先继承WebSecurityConfigurereAdapter,源码什么的太麻烦了我就不拔了。
然后重写configure中有httpconfigure中有AuthenticationManagerBuilder方法

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//我这里要定制首页所有人可以访问//authorize是授权的意思//添加相对应的匹配者有相对应的功能http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");//这些都是SpringSecurity中jar需要的//如果认证失败了就返回tologin页面http.formLogin();}//有授权就有认证//通过auth.inMemoryAuthentication认证//然后是账号密码等级//注意 需要and()拼接//在SpringSecurity5新增了加密方式//需要加密@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//数据正常情况是在数据库里面存//需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())//在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))//当然编码方式有很多种 我只是挑选了其中的一个auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3").and().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");}
}

四、用户注销和控制权限

1.配置pom.xml

pom.xml中新增springsecurity-thymeleaf整合包

<!--        thymeleaf和springsecurity整合包-->
<!--        作用:主要是将对应的等级匹配相对应的板块--><!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<!--       使用spring5的jar包可以解决显示不了sec:authorization的问题--><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version></dependency>

2.配置RouteController

这里因为导入了thymeleaf-springsecurity的缘故,
所以我们可以使用RouteController的方法进行登录和注册

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//我这里要定制首页所有人可以访问//authorize是授权的意思//添加相对应的匹配者有相对应的功能http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");//这里是新增的部分        //定制自动登录页http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");//如果认证失败了就返回tologin页面
//        http.formLogin();//开启注销功能http.logout().logoutSuccessUrl("/");}//有授权就有认证//通过auth.inMemoryAuthentication认证//然后是账号密码等级//注意 需要and()拼接//在SpringSecurity5新增了加密方式//需要加密@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//数据正常情况是在数据库里面存//需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())//在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))//当然编码方式有很多种 我只是挑选了其中的一个auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3").and().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");}
}

3.权限控制

<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
>
<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="stylesheet"><link th:href="@{/qinjiang/css/qinstyle.css}" 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}">首页</a><!--登录注销--><div class="right menu"><!--未登录-->
<!--                如果未登录-->
<!--                设置登录认证--><div sec:authorize="!isAuthenticated()"><a class="item" th:href="@{/toLogin}"><i class="address card icon"></i> 登录</a></div><div sec:authorize="isAuthenticated()"><a class="item">用户名:<span sec:authentication="name"></span>
<!--                        这里是principal.authorities认证-->权限: <span sec:authentication="principal.authorities"></span></a></div><div sec:authorize="isAuthenticated()"><a class="item" th:href="@{/logout}"><i class="sign-out icon"></i>注销</a></div><!--已登录<a th:href="@{/usr/toUserCenter}"><i class="address card icon"></i> admin</a>--></div></div></div><div class="ui segment" style="text-align: center"><h3>Spring Security Study by 秦疆</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}"><i class="bullhorn icon"></i> Level-1-1</a></div><div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div><div><a th:href="@{/level1/3}"><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}"><i class="bullhorn icon"></i> Level-2-1</a></div><div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div><div><a th:href="@{/level2/3}"><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}"><i class="bullhorn icon"></i> Level-3-1</a></div><div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div><div><a th:href="@{/level3/3}"><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>
  • 首先配置th:sec的环境
<html lang="en"xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
>
  • 然后,通过sec:authorize来控制属性
<div class="column" sec:authorize="hasRole('vip3')">
  • 这个是显示相对应的用户名和权限
           <div sec:authorize="isAuthenticated()"><a class="item">用户名:<span sec:authentication="name"></span>
<!--                        这里是principal.authorities认证-->权限: <span sec:authentication="principal.authorities"></span></a></div>

四、remeberme和主页定制

package com.kuang.config;
//继承了WebSecuritiyConfigurer并且实现了@EnableWebSecurity注解
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;
//这里是配置EnableSecurtiy适配器
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//我这里要定制首页所有人可以访问//authorize是授权的意思//添加相对应的匹配者有相对应的功能http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("vip1").antMatchers("/level2/**").hasRole("vip2").antMatchers("/level3/**").hasRole("vip3");//定制自动登录页http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");//如果认证失败了就返回tologin页面
//        http.formLogin();//开启注销功能http.logout().logoutSuccessUrl("/");http.csrf().disable();  //关闭跨站请求攻击的功能//勾选rememberme登录的时候,向cookie注入了的值http.rememberMe().rememberMeParameter("remember");  //记住我功能的实现}//有授权就有认证//通过auth.inMemoryAuthentication认证//然后是账号密码等级//注意 需要and()拼接//在SpringSecurity5新增了加密方式//需要加密@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//数据正常情况是在数据库里面存//需要在后面跟上passwordEncoder(new BCryptPasswordEncoder())//在密码框里面输入password(new BCryptPasswordEncoder().encode("123456"))//当然编码方式有很多种 我只是挑选了其中的一个auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("clearlove").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip3").and().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("ylsl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");}
}

SpringSecurity的学习流程相关推荐

  1. python流程控制语句-python学习 流程控制语句详解

    ###################### 分支语句 python3.5 ################ #代码的缩进格式很重要 建议4个空格来控制 #根据逻辑值(True,Flase)判断程序的 ...

  2. 软件测试系统学习流程和常见面试题

    在学习软件测试的时候你是否会感觉到不知从何下手? 今天教导你们软件测试学习的系统流程和面试常见的问题. 学习流程 一.必备技能 编程基础,能看懂前端页面,掌握一门语言:php/python/java等 ...

  3. 零基础学习Java的学习流程与学习误区

    学习Java编程技术肯定是以就业拿到高薪工作为主要目的的,可是高薪不会那么轻易拿到,这是一个简单的道理.没有付出就没有回报,在整个学习Java编程技术的过程中,你需要付出时间.精力.金钱.废话不多说合 ...

  4. 小白前端学习流程【爱创课堂专业前端培训】

    对于零基础非科班的同学来说,一个良好的前端学习流程和学习误区是需要我们去规避和计划的,爱创课堂目前专注于前端培训,总结了以下几点,给大家一个参考. 在开始学习之前你需要做到以下5点: 第一:需要达到什 ...

  5. 把飞书融入日常学习流程:一个人的飞书也挺好

    作为仍然奋斗在学术一线的学生,在很多同学和朋友眼里我一直是个喜欢折腾各种工具的「少数派」.除了每天必看的科研动态和文献之外,自己喜欢在摸鱼的时候折腾一些感兴趣的工具,用能提高效率的工具让自己拥有更多的 ...

  6. UI设计学习流程写给零基础学习的你

    UI设计是互联网时代的设计变革,有界面与人之间交互的时候就存在,但却没有现在这样对UI设计专业能力的重视.很多人现在学习UI设计,有的是看重UI设计月能薪破万的高薪资,有的人看重它未来大好的职业发展前 ...

  7. (一)什么是流程引擎?为什么学习流程引擎?

    activity(流程引擎)从零入门到实战学习 1.什么是流程引擎? 2.为什么需要学习流程引擎? 3.为什么选择activiti? 本编文章将详细介绍什么是流程引擎,为什么学习,以及为什么选择act ...

  8. UWB技术介绍及学习流程

    `UWB介绍及TOF学习流程 随着人们对室内定位的需求的日益增加,超宽带技术(UWB)也慢慢开始普及开来.目前已渗透到40多个垂直领域,包括工业.企业.汽车和消费类等市场.为了更好的学习UWB,笔者总 ...

  9. SpringSecurity登录认证流程

    SpringSecurity登录认证流程 目录 SpringSecurity简介 springSecurity登录认证流程 一.Springsecurity简介 ​ Spring Security是一 ...

  10. 转载别人的深度学习学习流程

    @转载别人的深度学习学习流程 转载链接:https://blog.csdn.net/qq_25024883/article/details/83507850 目录 Lecture I: Introdu ...

最新文章

  1. 使用 EOLINKER 进行接口测试的最佳路径 (下)
  2. TCP/IP 建立连接的过程
  3. 生日小助手的问答帮助——随时更新,长期有效……
  4. 实时可视化 Debug:VS Code 开源新工具,一键解析代码结构
  5. asp.net 中ashx、axd的区别
  6. mysql 字符转数值_深入MYSQL字符数字转换的详解
  7. 被裁之后才明白:有一种抗风险能力,叫做会讲故事
  8. STM32之独立看门狗原理
  9. 重磅!DigiX极客校园大赛今日启动,超百万巨奖激励AI精英!
  10. 汉诺塔问题的c语言递归
  11. matlab编写算法,Matlab 入门宝典 编程算法大全
  12. 初用vue遇到的一些问题
  13. 智慧城市的投资运营与评估
  14. CAN总线负载率原理及计算
  15. pytorch实用工具总结(GFLOPs如何计算)
  16. 出国留学成绩要求主要看点在雅思
  17. android模拟程序被杀死,Android模拟后台进程被杀
  18. HDMI接口之HPD(热拔插)
  19. 实现微信公众号二维码生成
  20. python用re模块实现数学公式计算

热门文章

  1. html5地球围着太阳转canvas动画
  2. segment-geospatial - 基于sam模型分割遥感影像
  3. 你是怎样把石头雕得飞起来的
  4. vant+vue 上传身份证正面和反面 Ocr识别校验反显
  5. 字节跳动Java金三银四解析:java什么培训机构靠谱
  6. 已解决 【k8s】reconnect to server error: dial tcp : connect: connection refused
  7. android lcd横竖屏幕配置
  8. 阿里Datawhale二手车价格预测——优胜奖方案总结(代码开源)
  9. 部分卫星主要传感器信息整理
  10. js 递归树结构,根据子节点获取父节点