SpringSecurity

在web开发中,安全第一位!(之前学过的:过滤器,拦截器)

功能性需求:否

做网站:安全应该什么时候考虑? 设计之初

  • 漏洞,隐私泄露~
  • 架构一旦确定~再加就会改动一堆代码

有名的有:shiro、SpringSecurity 注:两个很像,除了类和名字不一样

认证,授权(vip1, vip2,vip3)——原来需要在拦截器里写大量的配置**【用如上的框架只需要1,2行代码】**

SpringSecurity(身份验证和访问控制的框架——可自定义一些需求)

  • 功能权限
  • 访问权限
  • 菜单权限
  • … 拦截器,过滤器:大量的原生代码~冗余
  • mvc——spring——springboot——​​框架思想​

应用方式:

Aop(面向切面编程):横切~ 配置类~【我们不用改原来的代码,就能添加很多拦截器功能

  • 我们写一个SpringSecurity的配置类其实就好了
  • 包括前端也是通过thymeleaf来整合SpringSecurity

注:资源在gitee上找狂神的spring-security-material


09_14_第七阶段:微服务开发||01-SpringBoot||13SpringSecurity【观看狂神随笔】_安全

  • @Enablexxx:就可以开启某个功能

简单上手:

导入包:
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
创建config文件夹,及SecurityConfig类
//以下是固定的架子
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
}
}
实现的第一个功能:根据权限来【授权】
package com.kami.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;

//AOP : 拦截器(好用多了)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

//这里是链式编程
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才可以访问
//请求授权的规则
/*
1. 先认证一些请求:authorizeRequests()
2. 首页所有人能访问antMatchers("/").permitAll()
*/
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");

//没有权限默认会到登录页面,需要开启登录页面: formLogin()
//.loginPage("/toLogin"):用来定制登录页面
http.formLogin().loginPage("/toLogin");


}
}
实现的第二个功能:登录那些用户就可以【认证】那些页面
  • 注:登录的用户认证可以从数据库绑定,也可以在内存中绑定。
  • 注:需要给密码加密,负责会报错【密码编码:PasswordEncoder问题(springboot 2.1.x 之前版本可以直接用,现在会报错)】
  1. 在​​auth.inMemoryAuthentication()​​​后加上​​.passwordEncoder(new BCryptPasswordEncoder())​
  2. 将下面密码添加编码方式

例子中没有数据库,所以用到了内容认证

//上面SecurityConfig类中
//认证(这里用到了内存认证)
//密码编码:PasswordEncoder问题(springboot 2.1.x 之前版本可以直接用,现在会报错)
//解决方式:给密码加密
//在SpringSecurity 5.0+ 新增了很多加密方法
/*
1. inMemoryAuthentication():在内存中认证——也可以数据库认证
添加认证的用户:只有姓名,密码,权限三个属性
2. withUser("Carl"):用户姓名,roles("vip1", "vip3"):权限
3. and():拼接下一个

*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读~
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("Carl").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2", "vip3");
}
@Autowired
private DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// ensure the passwords are encoded properly
UserBuilder users = User.withDefaultPasswordEncoder();
auth
.jdbcAuthentication()
.dataSource(dataSource)
.withDefaultSchema()
.withUser(users.username("user").password("password").roles("USER"))
.withUser(users.username("admin").password("password").roles("USER","ADMIN"));
}
实现的第三个功能:【注销功能】
//注销:开启了注销功能
//这里是链式编程
@Override
protected void configure(HttpSecurity http) throws Exception {
//首页所有人可以访问,功能页只有对应有权限的人才可以访问
//请求授权的规则
/*
1. 先认证一些请求:authorizeRequests()
2. 首页所有人能访问antMatchers("/").permitAll()
*/
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");

//没有权限默认会到登录页面,需要开启登录页面: formLogin()
//.loginPage("/toLogin"):用来定制登录页面
http.formLogin().loginPage("/toLogin");

//注销:开启了注销功能,跳到首页
http.logout();
}
  • index.html页面中
<!--登录注销-->
<div class="right menu">
<!--未登录-->
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>

<!--注销代码-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>

<!--已登录
<a th:href="@{/usr/toUserCenter}">
<i class="address card icon"></i> admin
</a>
-->
</div>
实现的第四个功能:【权限控制页面的展示(有多少权限,显示多少页面)】

thymeleaf与Spring Security整合——就可以在thymeleaf中写一些Security的操作

<!--thymeleaf和security整合包-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>

index导入了命名空间

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

编写index

<!--登录注销-->
<div class="right menu">

<!--如果未登录-->
<!--isAuthenticated()——判断是否登录过了-->
<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>
<!--角色:<span sec:authentication=""></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>
  • 注:如果都显示,可能是Spring boot版本过高导致
  • 降到2.0.9

注:登录失败可能存在的原因

  • 防止网站被攻击
protected void configure(HttpSecurity http) throws Exception{ //之间写


//防止网站被攻击 不用get post
//登录失败可能存在的原因
http.csrf().disable(); //关闭,跨站请求伪造功能


}

菜单根据用户的角色,显示相应的页面

<!--菜单根据用户的角色,显示相应的页面-->
<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>
记住我功能
//记住我功能
protected void configure(HttpSecurity http) throws Exception {
http.rememberMe();
}

登录按钮的实现

@Override
protected void configure(HttpSecurity http) throws Exception {
//.loginPage("/toLogin"):用来定制登录页面
http.formLogin().loginPage("/toLogin");
}
//login.html页面中
<form th:action="@{/toLogin}" method="post">
————————————————
<div class="field">
<input type="checkbox" name="remember"> 记住我
</div>