SpringSecurity

  1. SpringSecurity

11.1 SpringSecurity简介

Spring 是一个非常流行和成功的 Java 应用开发框架。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分。用户认证指的是验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。

11.2 实验环境搭建

1、新建springboot项目

引入web模块、thymeleaf模块


    org.springframework.boot
    spring-boot-starter-web

    org.springframework.boot
    spring-boot-starter-thymeleaf
    2.5.6

2、导入静态资源

index.html
|views
  |level1
     1.html
     2.html
     3.html
  |level2
     1.html
     2.html
     3.html
  |level3
     1.html
     2.html
     3.html
  Login.html

3、controller跳转

package com.dzj.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 toIndex(){
        return "index";
    }
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "views/login";
    }
    @RequestMapping("/level1/{id}")
    public String toLevel1(@PathVariable("id")int id){
        return "views/level1/"+id;
    }
    @RequestMapping("/level2/{id}")
    public String toLevel2(@PathVariable("id")int id){
        return "views/level2/"+id;
    }
    @RequestMapping("/level3/{id}")
    public String toLevel3(@PathVariable("id")int id){
        return "views/level3/"+id;
    }
}

11.3 认识SpringSecurity

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

记住几个类:

  • WebSecurityConfigurerAdapter:自定义Security策略
  • AuthenticationManagerBuilder:自定义认证策略
  • @EnableWebSecurity:开启WebSecurity模式

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

“认证”(Authentication)

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

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

“授权” (Authorization)

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

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

1、 认证和授权

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

引入 Spring Security 模块


    org.springframework.boot
    spring-boot-starter-security

编写SpringSecurity配置类

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

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

https://docs.spring.io/spring-security/site/docs/5.5.3.RELEASE/reference/html5

进行全文搜索: WebSecurityConfigurerAdapter

SpringSecurity

编写基础配置类

package com.dzj.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 {

  }
    //定义认证规则
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {

  }
}

定制请求的授权规则

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

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

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

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

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

SpringSecurity

查看刚才登录页的注释信息,我们可以定义认证规则,重写configure(AuthenticationManagerBuilder auth)方法

//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {

   //在内存中定义,也可以在jdbc中去拿....

   auth.inMemoryAuthentication()
          .withUser("dengzj").password("aadzj").roles("vip2","vip3")
          .and()
          .withUser("root").password("aadzj").roles("vip1","vip2","vip3")
          .and()
          .withUser("guest").password("aadzj").roles("vip1","vip2");
}

测试,我们可以使用这些账号登录进行测试!发现会报错!There is no PasswordEncoder mapped for the id “null”

SpringSecurity

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

//认证
//密码编码:passwordEncoder,需要对密码进行加密处理
//在SpringSecurity 5.0+ 中新增了很多的加密方法~
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
   //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
   //spring security 官方推荐的是使用bcrypt加密方式。
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
    .withUser("dengzi").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip2","vip3")
    .and()
    .withUser("root").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip1","vip2","vip3")
    .and()
    .withUser("guest").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip1");
}

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

2、权限控制和注销

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

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....

   //开启自动配置的注销的功能
      // /logout 注销请求
   http.logout();
}

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


     注销

测试一下,登录成功后点击注销,发现注销完毕会跳转到登录页面!

但是,如果想注销成功后,依旧可以跳转到首页,该怎么处理呢?

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

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

根据真实网站需求定制

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

我们需要结合thymeleaf中的一些功能导入security-thymeleaf整合包


    org.thymeleaf.extras
    thymeleaf-extras-springsecurity5
    3.0.4.RELEASE

sec:authorize=”isAuthenticated()” :判断是否认证登录,显示不同的信息

修改前端页面(index.html)

导入命名空间

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

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


             登录

            用户名:
            角色:

             注销

重启测试,登录成功后确实显示了我们想要的页面

关闭csrf功能

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

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

角色功能块认证 sec:authorize=”hasRole(‘xxx’)”


                    Level 1

                     Level-1-1
                     Level-1-2
                     Level-1-3

                    Level 2

                     Level-2-1
                     Level-2-2
                     Level-2-3

                    Level 3

                     Level-3-1
                     Level-3-2
                     Level-3-3

登录测试,成功!权限控制和注销搞定!

3、记住我功能

现在的情况,我们只要登录之后,关闭浏览器,再登录,就会让我们重新登录,但是很多网站的情况,就是有一个记住密码的功能,这个该如何实现呢?

开启记住我功能

//定制请求的授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {

    // ......

   //记住我
   http.rememberMe();

}

启动测试,查看浏览器的cookie

再次启动项目测试,发现登录页多了一个记住我功能,登录之后关闭浏览器,然后重新打开浏览器访问,发现用户依旧存在!

如何实现的呢?其实非常简单,我们可以查看浏览器的cookie

SpringSecurity

注销时cookie的删除 spring security 帮我们自动删除 cookie

SpringSecurity

结论

登录成功后,将cookie发送给浏览器保存,以后登录带上这个cookie,只要通过检查就可以免登录了,如果点击注销,则会删除这个cookie。

4、定制登录页

现在这个登录页面都是spring security 默认的,怎么样可以使用我们自己写的Login界面呢?

在刚才的登录页配置后面指定 loginpage

http.formLogin().loginPage("/toLogin");
//http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");

前端也需要指向我们自己定义的 login 请求


         登录

login.html页面配置

请求登录,需要将这些信息发送到哪里,我们也需要配置,login.html 配置提交请求及方式,方式必须为post,在 loginPage()源码中的注释上有写明:

SpringSecurity

        Username

        Password

        记住我

接收登录的用户名和密码的参数

这个请求提交上来,我们还需要验证处理,怎么做呢?我们可以查看formLogin()方法的源码!我们配置接收登录的用户名和密码的参数!

http.formLogin()
  .usernameParameter("username")
  .passwordParameter("password")
  .loginPage("/toLogin")
  .loginProcessingUrl("/login"); // 登陆表单提交请求

在登录页增加 记住我的多选框


    记住我

后端验证处理 rememberMe()

//开启记住我功能,默认保存时间两周
http.rememberMe().rememberMeParameter("remember");

测试,OK!搞定!

5、完整配置代码(SecurityConfig.java)

package com.dzj.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 SecurityConfig extends WebSecurityConfigurerAdapter {

    //定义授权规则
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //首页所有人可以访问,功能也只有有对应权限的人才能访问
        //请求授权的规则
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");
        //没有权限会跳转到登录页,需要开启登录的页面
        http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");

        //防止网站攻击
        http.csrf().disable();  //关闭csrf功能,登录失败存在的原因

        //注销
        http.logout().logoutSuccessUrl("/"); //注销成功后跳转到哪个位置

        //开启记住我功能,默认保存时间两周
        http.rememberMe().rememberMeParameter("remember");
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //在内存中定义,也可以在jdbc中去拿....

       //Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
       //要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密码进行某种方式加密
       //spring security 官方推荐的是使用bcrypt加密方式。

        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
        .withUser("dengzi").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip2","vip3")
        .and()
        .withUser("root").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip1","vip2","vip3")
        .and()
        .withUser("guest").password(new BCryptPasswordEncoder().encode("aadzj")).roles("vip1");
    }
}

Original: https://www.cnblogs.com/aadzj/p/15636802.html
Author: 小公羊
Title: SpringSecurity

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/612339/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • LeetCode-210. 课程表 II

    题目来源 题目详情 现在你总共有 numCourses 门课需要选,记为 0 到 numCourses – 1。给你一个数组 prerequisites ,其中 prerequis…

    Linux 2023年6月7日
    089
  • LDD3第三章学习笔记

    思维导图 需求 实现一个设备/dev/scull,这个设备能用dd, cp, cat和Shell的IO重定向功能操作。 设备号 Linux用主次两个设备号去唯一的表示一个设备。其中…

    Linux 2023年6月7日
    0106
  • html2canvas生成并下载图片

    html <div id="downChart"> div> jq new html2canvas(document.getElementBy…

    Linux 2023年6月7日
    088
  • OpenSSL测试-大数

    任务详情 在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务 基于OpenSSL的大数库计算2的N次方,N为你学号的后四位(5’) 基于…

    Linux 2023年6月8日
    0102
  • gitlab服务yum源安装详细步骤(centos7)

    gitlab服务yum源安装详细步骤(centos7) 概述 GitLab是利用Ruby on Rails一个开源的版本管理系统,实现一个自托管的Git项目仓库,可通过Web界面进…

    Linux 2023年6月8日
    097
  • su与su -,sudo 的区别

    “sudo” , “su” , “su – ” 区别; 一、sudo是一种权限管理机制,依赖于/…

    Linux 2023年6月13日
    0133
  • 配置管理docker对象和守护进程

    使用 Docker 的主要工作是创建和使用各类对象:镜像、容器、网络、卷等。 1、Docker对象的标记 标记(Label):是一种将元数据应用于Docker对象(镜像、容器、网络…

    Linux 2023年6月8日
    090
  • centos 8及以上安装mysql 8.0

    本文适用于centos 8及以上安装mysql 8.0,整体耗时20分钟内,不需要FQ 1.环境先搞好 systemctl stop firewalld //关闭防火墙 syste…

    Linux 2023年6月7日
    0111
  • 如何解决 QMediaPlayer 占用歌曲导致 PermissionError: [Error 13] 的问题

    问题描述 当我们使用 QMediaPlayer 播放歌曲时,歌曲文件的句柄会被占用。如果想使用 mutagen 库对正在播放地歌曲进行数据写入,就会出现下述问题: Tracebac…

    Linux 2023年6月7日
    095
  • Linux之NFS

    一、什么是NFS 共享存储,文件服务器 1.1 基本概述 NFS是Network File System的缩写及网络文件系统。NFS主要功能是通过局域网络让不同的主机系统之间可以共…

    Linux 2023年5月27日
    083
  • 关闭linux内核反向路由

    route -n Kernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface0.0….

    Linux 2023年6月8日
    0108
  • [20211108]索引分裂块清除日志增加(唯一索引)2.txt

    [20211108]索引分裂块清除日志增加(唯一索引)2.txt –//链接http://blog.itpub.net/267265/viewspace-2840853…

    Linux 2023年6月13日
    088
  • 【证券从业】金融基础知识-第五章 债券02

    注1:后续学习并整理到第八章,全书完结后再合并成一个笔记进行源文件分享 注2:本章内容巨多,大约分为两篇文章记录消化 posted @2022-06-09 23:55 陈景中 阅读…

    Linux 2023年6月13日
    093
  • CentOS 7安装FTP服务器

    修改 vsftpd.conf配置文件,禁用匿名用户访问ftp服务器 vim /etc/vsftpd/vsftpd.conf 将配置文件中的 anonymous_enable=YES…

    Linux 2023年5月27日
    0117
  • Color 16 Base Code 颜色代码大全

    颜色预览表,请参考以下图片。 十六进制颜色编码字符串如下所示(前置的英语单词都是颜色) ‘aliceblue’: ‘#F0F8FF’…

    Linux 2023年6月7日
    0129
  • SUPERVISOR监控tomcat配置文件

    下方为Supervisor管理tomcat的配置,多注意红色位置路径修改: [program:tomcat] ; 管理的子程序名字,要和项目有关联,不能乱写 command=/us…

    Linux 2023年6月6日
    0102
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球