1-新建一个项目,先不引入security,引入,

2-resources->templates->welcome.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" ><title>sdfasfa</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
<hr><h3>普通武功秘籍</h3>
<ul><li><a th:href="@{/level1/1}">罗汉拳</a></li><li><a th:href="@{/level1/2}">武当长拳</a></li><li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul><h3>高级武功秘籍</h3>
<ul><li><a th:href="@{/level2/1}">太极拳</a></li><li><a th:href="@{/level2/2}">七伤拳</a></li><li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul><h3>绝世武功秘籍</h3>
<ul><li><a th:href="@{/level3/1}">葵花宝典</a></li><li><a th:href="@{/level3/2}">龟派气功</a></li><li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</body>
</html>

3-resources->templates->pages->level1->1.html,2.html,3.html

...

resources->templates->pages->level2->1.html,2.html,3.html

resources->templates->pages->level3->1.html,2.html,3.html

4-新建controller包KungfuController类

package com.example.springboot05security.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;@Controller
public class KungfuController {private final String PREFIX = "pages/";/*** 欢迎页* @return*/@GetMapping("/")public String index(){return "welcome";}/*** 登录页* @return*/@GetMapping("/userlogin")public String loginPage(){return PREFIX+"login";}/*** level1页面映射* @param path* @return*/@GetMapping("/level1/{path}")public String level1(@PathVariable("path")String path){return PREFIX+"level1/"+path;}/*** level2页面映射* @param path* @return*/@GetMapping("/level2/{path}")public String level2(@PathVariable("path")String path){return PREFIX+"level2/"+path;}/*** level3页面映射* @param path* @return*/@GetMapping("/level3/{path}")public String level3(@PathVariable("path")String path){return PREFIX+"level3/"+path;}
}

5-引入SpringSecurity

pom.xml中新增

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>

6-编写SpringSecurity的配置类

spring官网->PROJECTS->SPRING SECURITY

访问https://docs.spring.io/spring-security/site/docs/current/guides/html5/

新建config包MySecurityConfig类

package com.example.springboot05security.config;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
}

7-控制请求的访问权限

package com.example.springboot05security.config;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
public class MySecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//super.configure(http);      父类方法需要注释掉//定制请求的授权规则   .permitAll() 允许所有用户访问   .hasRole("xxx") 只有xxx用户才能访问http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("VIP1").antMatchers("/level2/**").hasRole("VIP2").antMatchers("/level3/**").hasRole("VIP3");}
}

此时,访问首页时,

访问其他页面时.

8-加入登录

HttpSecurity中,

/*** Specifies to support form based authentication. If* {@link FormLoginConfigurer#loginPage(String)} is not specified a default login page* will be generated.** <h2>Example Configurations</h2>** The most basic configuration defaults to automatically generating a login page at* the URL "/login", redirecting to "/login?error" for authentication failure. The* details of the login page can be found on* {@link FormLoginConfigurer#loginPage(String)}** <pre>* @Configuration* @EnableWebSecurity* public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {**   @Override*     protected void configure(HttpSecurity http) throws Exception {*         http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin();*     }**     @Override*     protected void configure(AuthenticationManagerBuilder auth) throws Exception {*         auth.inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;);*   }* }* </pre>** The configuration below demonstrates customizing the defaults.** <pre>* @Configuration* @EnableWebSecurity* public class FormLoginSecurityConfig extends WebSecurityConfigurerAdapter {**  @Override*     protected void configure(HttpSecurity http) throws Exception {*         http.authorizeRequests().antMatchers(&quot;/**&quot;).hasRole(&quot;USER&quot;).and().formLogin()*              .usernameParameter(&quot;username&quot;) // default is username*                .passwordParameter(&quot;password&quot;) // default is password*                .loginPage(&quot;/authentication/login&quot;) // default is /login with an HTTP get*                .failureUrl(&quot;/authentication/login?failed&quot;) // default is /login?error*               .loginProcessingUrl(&quot;/authentication/login/process&quot;); // default is /login*                                                                       // with an HTTP*                                                                        // post*    }**     @Override*     protected void configure(AuthenticationManagerBuilder auth) throws Exception {*         auth.inMemoryAuthentication().withUser(&quot;user&quot;).password(&quot;password&quot;).roles(&quot;USER&quot;);*   }* }* </pre>** @see FormLoginConfigurer#loginPage(String)** @return the {@link FormLoginConfigurer} for further customizations* @throws Exception*/public FormLoginConfigurer<HttpSecurity> formLogin() throws Exception {return getOrApply(new FormLoginConfigurer<>());}

9-重写定义认证规则方法

package com.example.springboot05security.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 MySecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {//super.configure(http);      父类方法需要注释掉//定制请求的授权规则   .permitAll() 允许所有用户访问   .hasRole("xxx") 只有xxx用户才能访问http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/level1/**").hasRole("VIP1").antMatchers("/level2/**").hasRole("VIP2").antMatchers("/level3/**").hasRole("VIP3");//开启自动配置的登录功能,如果没有登录,没有权限就会来到自动生成的登录页面http.formLogin(); //  /login来到登录页,重定向到/login?error表示登录失败}//定义认证规则@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {//super.configure(auth);auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2").and().withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3").and().withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");}
}

即可完成登录及认证与授权

10-注销功能

MySecurityConfig类中添加

welcome.html中添加

<form th:action="@{/logout}" method="post"><input type="submit" value="注销" />
</form>

修改MySecurityConfig类,使注销成功之后返回首页

11-页面使用权限控制

查看依赖

点进starter-parent

进入dependencies

可以看到

如果需要换版本

可以在pom中写入

此时出现sec标签不生效的问题:

解决:

pom.xml中添加

        <!--引入>thymeleaf-extras-springsecurity5--><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version></dependency>

welcome.html如下

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" ><title>sdfasfa</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()"><h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/login}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()"><h2><span sec:authentication="name"></span>,您好,您的角色有:<span sec:authentication="principal.authorities"></span></h2><form th:action="@{/logout}" method="post"><input type="submit" value="注销" /></form>
</div><hr><div sec:authorize="hasRole('VIP1')"><h3>普通武功秘籍</h3><ul><li><a th:href="@{/level1/1}">罗汉拳</a></li><li><a th:href="@{/level1/2}">武当长拳</a></li><li><a th:href="@{/level1/3}">全真剑法</a></li></ul>
</div><div sec:authorize="hasRole('VIP2')"><h3>高级武功秘籍</h3><ul><li><a th:href="@{/level2/1}">太极拳</a></li><li><a th:href="@{/level2/2}">七伤拳</a></li><li><a th:href="@{/level2/3}">梯云纵</a></li></ul>
</div><div sec:authorize="hasRole('VIP3')"><h3>绝世武功秘籍</h3><ul><li><a th:href="@{/level3/1}">葵花宝典</a></li><li><a th:href="@{/level3/2}">龟派气功</a></li><li><a th:href="@{/level3/3}">独孤九剑</a></li></ul>
</div></body>
</html>

12-开启记住我功能

//登录成功时,将cookie发送给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录,点击注销会删除cookie

注销的时候

13-定制登录页

修改welcome.html

修改MySecurityConfig

templates->pages文件夹下新建login.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>定制的登录页</title>
</head>
<body><h1 align="center">欢迎登录武林秘籍管理系统</h1><hr><div align="center"><form th:action="@{/userlogin}" method="post">用户名:<input name="user" /><br>密码:<input name="pwd"><br><input type="submit" value="登录"></form></div>
</body>
</html>

或者:

14-定制页面添加remember me功能

springboot安全之整合spring security相关推荐

  1. 31 | SpringBoot安全之整合Spring Security

    一.安全 应用程序的两个主要区域是"认证"和"授权"(或者访问控制),这两个主要区域是安全的两个目标. 身份验证意味着确认您自己的身份,而授权意味着授予对系统的 ...

  2. 八、springboot整合Spring Security

    springboot整合Spring Security 简介 Spring Security是一个功能强大且可高度自定义的身份验证和访问控制框架.它是保护基于Spring的应用程序的事实标准. Spr ...

  3. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离

    在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与权限管理. ...

  4. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离--筑基中期

    写在前面 在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与 ...

  5. SpringBoot 整合 Spring Security 实现安全认证【SpringBoot系列9】

    SpringCloud 大型系列课程正在制作中,欢迎大家关注与提意见. 程序员每天的CV 与 板砖,也要知其所以然,本系列课程可以帮助初学者学习 SpringBooot 项目开发 与 SpringCl ...

  6. SpringBoot整合Spring Security【超详细教程】

    好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/Lee/DayDayUP,欢迎Star,更多文章请前往:目录导航 前言 Spring Security是一个 ...

  7. spring boot整合spring security笔记

    最近自己做了一个小项目,正在进行springboot和spring Security的整合,有一丢丢的感悟,在这里分享一下: 首先,spring boot整合spring security最好是使用T ...

  8. 认证与授权流程与spring boot整合 spring security(1)

    一   spring security 1.1 spring security的作用 Spring Security所解决的问题就是安全访问控制,而安全访问控制功能其实就是对所有进入系统的请求进行拦截 ...

  9. springboot2 war页面放在那_Spring Boot2 系列教程(三十三)整合 Spring Security

    Spring Security 是 Spring 家族中的一个安全管理框架,实际上,在 Spring Boot 出现之前,Spring Security 就已经发展了多年了,但是使用的并不多,安全管理 ...

最新文章

  1. 深度丨AlphaGo Zero的启示:监督学习和无监督学习的利弊
  2. VTS工具测试指定的testcase函数(以VtsHalKeymasterV4_0TargetTest为例)
  3. 【PS】WBS结算到建工程问题
  4. 003thinkphp 数据库查询及表关联
  5. Linux中断处理与定时器
  6. 插入排序--Java
  7. Oracle分区表之创建维护分区表索引的详细步骤
  8. 【不行你来找我】webstorm设置背景图片
  9. delphi2010中FastReport的安装方法
  10. MySQL错误Another MySQL daemon already running with the same unix socket.
  11. think in java 读书笔记 1 ——移位
  12. BIOS不识别硬盘,DIY解决希捷固件门(图解)
  13. Spring框架学习(十)SSM框架整合
  14. Linux 发展史小览
  15. java微信录音arm转mp3_使用FFmpeg将微信录音 amr格式 转 MP3格式
  16. 在命令窗中查询当前电脑IP
  17. 苹果笔记本双系统OS和win10,在win10下罗技M558蓝牙提示输入码无效
  18. 用c语言求解一元二次方程(共轭根除外)
  19. BLE协议--ATT、GATT
  20. CocosCreater 教程(下)

热门文章

  1. 用python实现自动化办公------Excel操作
  2. Shiro--解决is not eligible for getting processed by all BeanPostProcessors
  3. HDMI原理详解以及时序流程(视频是三对差分信号,音频Audio是PCM级(无压缩)传输,包含在数据包内,依靠协议规定采样)HDMI可以传输RGB与YUV两种格式
  4. 5 张图带你理解 RocketMQ 消费者启动过程
  5. centos7 team 绑定
  6. 用户与OA厂商:一荣俱荣,一损俱损
  7. 将列表按字母排序如通讯录
  8. 2019年秋季学期实验室安全考试2
  9. html5 图片局部马赛克,javascript - JS实现马赛克图片效果完整示例
  10. CodeM资格赛C 优惠券 题解