SpringSecurity基础

SpringSecurity

学习思路:了解是什么–> 看官网简介–> 简单快速阅读官方文档

springboot:

  • 导入maven依赖
  • 配置相关文件
  • 测试代码编写

安全框架
在Web开发中,安全一直是十分重要的一个环节!也属于非功能性需求!组件框架来去实现!
防御跨站脚本攻击!用户名密码验证!(集成了一些类,来自动进行这些操作)
管理员可以查看一切,普通用户功能比较少!(自定义菜单 用户表 用户角色表 角色表 角色权限表 权限表)
市面上比较知名的框架:
Shiro(用的十分多,功能更加强大)
SpringSecurity(用得也很多,但是没有那么强大,他可以和Spring无缝结合,十分的方便,基本的功能全都用!)

在这里插入图片描述
pom依赖:

<dependencies>
  <!-- ... other dependency elements ... -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
</dependencies>

原理: 本质是一个Filter过滤器链

在这里插入图片描述

去找java configuration的,关于Http相关的配置
在这里插入图片描述

用户密码验证的地方:

在这里插入图片描述

SpringSecurity的授权流程

所有请求url -> BasicAuthenticationFilter / UsernamePasswordAuthenticationFilter -> FilterSecurityInterceptor -> BasicAuthenticationFilter / UsernamePasswordAuthenticationFilter -> FilterSecurityInterceptor -> controller层

所有请求都默认进入 BasicAuthenticationFilter 过滤器进行过滤,然后进入 FilterSecurityInterceptor 过滤器进行权限验证,如果在 FilterSecurityInterceptor 中权限验证就会跳转到 /login 请求进行处理,然后在进入 BasicAuthenticationFilter 或者 UsernamePasswordAuthenticationFilter 过滤器,再进入 FilterSecurityInterceptor,只有当 FilterSecurityInterceptor 过滤通过了才会跳转到之前的请求路径

技巧01:如果在 FilterSecurityInterceptor 中抛出了异常就会跳转到 ExceptionTranslationFilter 进行相应的处理

在这里插入图片描述

认证和授权详解

认证:就是识别用户身份

授权:就是给用户角色,以此来操作一些页面

1、建立项目!
2、导入我们的前端资源!

在这里插入图片描述

如果使用shiro 会配置3个类,十分麻烦!SpringSecurity只要简单的配置即可!
3、确定我们导入SpringSecurity的配置,然后加上一个注解即可 @EnableWebSecurity 主类中加上即可,或者配置类中加入即可

@SpringBootApplication
@EnableWebSecurity
public class MyblogsystemApplication {
   

    public static void main(String[] args) {
   
        SpringApplication.run(MyblogsystemApplication.class, args);
    }

}

4、启动项目,发现自动跳转到了登录页面:默认的用户名 user
密码在我们启动项目时候输出了!
在这里插入图片描述

5、配置基本的请求过滤

@Configuration
public class SecurityConfigure  extends WebSecurityConfigurerAdapter {
   
@Override
protected void configure(HttpSecurity http) throws Exception {
   
  // 不同用户访问内容不同! 这里,过滤器,登录注销规则,安全配置,OAuth2配置
  // 我们平时只需要配置一些基本的规则即可!
  // 首页是允许所有人访问的!
 
  // 自定定制授权的规则!
  http.authorizeRequests()
   .antMatchers("/").permitAll()
   .antMatchers("/level1/**").hasRole("vip1")
   .antMatchers("/level2/**").hasRole("vip2")
   .antMatchers("/level3/**").hasRole("vip3");
}

在这里插入图片描述

6、发现问题,跳转到了403 ,权限不允许,我们希望它应该跳转到登录页!

// 登录 /login跳转到登录页 /login?error 登录失败
http.formLogin();
// 如果没有登录,自动跳转到登录页面!

7、我们来配置一些登录的用户进行测试

在这里插入图片描述

// 定义用户的认证规则 (角色,密码....)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
  // 内存中定义用户信息
  auth.inMemoryAuthentication() // 一个人可以拥有多个角色!
   .withUser("coding").password("123456").roles("vip1","vip2")
   .and()
   .withUser("kuangshen").password("123456").roles("vip1","vip2","vip3")
   .and()
   .withUser("guest").password("123456").roles("vip1");
}

重启访问使用以上账号登录测试!发现500错误,密码没有加密!

在这里插入图片描述

8、找到我们的密码加密的接口 PasswordEncoder

在这里插入图片描述

发现很多的加密方法,SpringSecurity推荐我们使用 BCryptPasswordEncoder

在这里插入图片描述

给我们的用户增加密码加密,然后再次启动测试!

// 定义用户的认证规则 (角色,密码....)
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
  // 内存中定义用户信息
  // 我们只定义了用户的密码加密,但是没有定义用户的认证规则的加密方式
  auth.inMemoryAuthentication()
   .passwordEncoder(new BCryptPasswordEncoder()) // 使用的加密方式要对应下面面的
加密方式
    // 一个人可以拥有多个角色!
   .withUser("coding")
   .password(new BCryptPasswordEncoder().encode("123456"))  // 密码的加密
   .roles("vip1","vip2")
   .and()
   .withUser("kuangshen")
   .password(new BCryptPasswordEncoder().encode("123456"))
   .roles("vip1","vip2","vip3")
   .and()
   .withUser("guest")
   .password(new BCryptPasswordEncoder().encode("123456"))
   .roles("vip1");
}

9、注销!

<a class="item" th:href="@{/logout}">
  <i class="address card icon"></i> 注销
</a>

发现其实SpringSecurity已经帮我们将全部的用户登录退出的规则都定义好了!
在这里插入图片描述

配置登出成功的页面

// 注销 开启默认的注销功能!
http.logout().logoutSuccessUrl("/"); // 注销成功后跳转至首页!

重启项目测试,登录和退出!

登录页定制记住我

功能:用户没有登录的时候,就只显示导航栏!如果登录了,只显示自己权限能够看到的东西
根据不同的权限,前端展示不同的功能!

springsecrity 和 thymealef 结合:

1、导入依赖

在这里插入图片描述

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

2、修改前端页面
导入命名空间约束 (如果不生效,可以尝试重启)

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

前端页面:

<!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="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">
        <!--核心类:Authentication-->
        <!-- 如果未登录就显示登陆按钮 -->
        <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">
            <!--<i class="address card icon"></i>-->
           用户名:<span sec:authentication="principal.username">
</span> &nbsp;
           角色:<span
sec:authentication="principal.authorities"></span>
          </
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值