狂神说SpringBoot:SpringSecurity笔记及thymeleaf静态资源(二)

简介: 狂神说SpringBoot:SpringSecurity笔记及thymeleaf静态资源(二)

2.认识SpringSecurity


Spring Security 是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入 spring-boot-starter-security 模块,进行少量的配置,即可实现强大的安全管理!


记住几个类:


WebSecurityConfigurerAdapter:自定义Security策略


AuthenticationManagerBuilder:自定义认证策略


@EnableWebSecurity:开启WebSecurity模式


Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。


“认证”(Authentication)


身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。


身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。


“授权” (Authorization)


授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,几乎任何内容)的完全权限。


这个概念是通用的,而不是只在Spring Security 中存在。


3.认证和授权

目前,我们的测试环境,是谁都可以访问的,我们使用 Spring Security 增加上认证和授权的功能


1、引入 Spring Security 模块


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


2、编写 Spring Security 配置类


参考官网:https://spring.io/projects/spring-security


查看我们自己项目中的版本,找到对应的帮助文档:


https://docs.spring.io/spring-security/site/docs/5.3.0.RELEASE/reference/html5   #servlet-applications 8.16.4


image.png


3、编写基础配置类


package com.kuang.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 // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
}


4、定制请求的授权规则


@Override
protected void configure(HttpSecurity http) throws Exception {
// 定制请求的授权规则
// 首页所有人可以访问
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
}


5、测试一下:发现除了首页都进不去了!因为我们目前没有登录的角色,因为请求需要登录的角色拥有对应的权限才可以!


6、在configure()方法中加入以下配置,开启自动配置的登录功能!


// 开启自动配置的登录功能
// /login 请求来到登录页
// /login?error 重定向到这里表示登录失败
http.formLogin();


7、测试一下:发现,没有权限的时候,会跳转到登录的页面!


image.png


8、查看刚才登录页的注释信息;


我们可以定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法


//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中定义,也可以在jdbc中去拿....
auth.inMemoryAuthentication()
.withUser("kuangshen").password("123456").roles("vip2","vip3")
.and()
.withUser("root").password("123456").roles("vip1","vip2","vip3")
.and()
.withUser("guest").password("123456").roles("vip1","vip2");
}


9、测试,我们可以使用这些账号登录进行测试!发现会报错!


There is no PasswordEncoder mapped for the id “null”


image.png


10、原因,我们要将前端传过来的密码进行某种方式加密,否则就无法登录,修改代码


//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中定义,也可以在jdbc中去拿....
//Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
//要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
//spring security 官方推荐的是使用bcrypt加密方式。
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
}


11、测试,发现,登录成功,并且每个角色只能访问自己认证下的规则!搞定


4.权限控制和注销


1、开启自动配置的注销的功能


//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//....
//开启自动配置的注销的功能
// /logout 注销请求
http.logout();
}

2、我们在前端,增加一个注销的按钮,index.html 导航栏中


3、我们可以去测试一下,登录成功后点击注销,发现注销完毕会跳转到登录页面!


4、但是,我们想让他注销成功后,依旧可以跳转到首页,该怎么处理呢?


// .logoutSuccessUrl("/"); 注销成功来到首页
http.logout().logoutSuccessUrl("/");


5、测试,注销完毕后,发现跳转到首页OK


6、我们现在又来一个需求:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮!还有就是,比如kuangshen这个用户,它只有 vip2,vip3功能,那么登录则只显示这两个功能,而vip1的功能菜单不显示!这个就是真实的网站情况了!该如何做呢?


我们需要结合thymeleaf中的一些功能


sec:authorize="isAuthenticated()":是否认证登录!来显示不同的页面


Maven依赖:

<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>


org.thymeleaf.extras


thymeleaf-extras-springsecurity5


3.0.4.RELEASE



7、修改我们的 前端页面


导入命名空间


xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"

修改导航栏,增加认证判断

<!--登录注销-->
<div class="right menu">
<!--如果未登录-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/login}">
<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}">
<i class="address card icon"></i> 注销
</a>
</div>
</div>

8、重启测试,我们可以登录试试看,登录成功后确实,显示了我们想要的页面;


9、如果注销404了,就是因为它默认防止csrf跨站请求伪造,因为会产生安全问题,我们可以将请求改为post表单提交,或者在spring security中关闭csrf功能;我们试试:在 配置中增加 http.csrf().disable();


http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
http.logout().logoutSuccessUrl("/");


10、我们继续将下面的角色功能块认证完成


<!-- sec:authorize="hasRole('vip1')" -->
<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>


11、测试一下!


  1. 12、权限控制和注销搞定!
相关文章
|
3月前
|
存储 安全 Java
SpringBoot搭建Spring Security 入门
SpringBoot搭建Spring Security 入门
115 0
|
2月前
|
存储 安全 Java
Spring Boot整合Spring Security--学习笔记
Spring Boot整合Spring Security--学习笔记
55 1
|
4月前
|
JavaScript 前端开发 Java
SpringBoot之静态资源规则与定制化
SpringBoot之静态资源规则与定制化
|
4月前
|
移动开发 Java HTML5
Springboot web静态资源配置
Springboot web静态资源配置
57 0
|
3月前
|
前端开发 安全 Java
SpringBoot 实现登录验证码(附集成SpringSecurity)
SpringBoot 实现登录验证码(附集成SpringSecurity)
|
25天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
25天前
|
SQL 前端开发 JavaScript
Spring Boot + Thymeleaf 使用PageHelper实现分页
Spring Boot + Thymeleaf 使用PageHelper实现分页
|
3月前
|
前端开发 JavaScript Java
基于Springboot+SpringSecurity+Activiti7实现的工作流系统可方便二次开发(附完整源码)
基于Springboot+SpringSecurity+Activiti7实现的工作流系统可方便二次开发(附完整源码)
59 0
|
3月前
|
SQL 前端开发 Java
springboot + thymeleaf + layui 初尝试
springboot + thymeleaf + layui 初尝试
|
4月前
|
安全 Java Spring
springboot整合spring security 实现用户登录注册与鉴权全记录
【1月更文挑战第11天】springboot整合spring security 实现用户登录注册与鉴权全记录
101 2