Spring Security基础详细介绍

目录

1. SpringSecurity 框架简介

1.1 概要

1.2 历史

1.3 同款产品对比

1.3.1 Spring Security

1.3.2 Shiro

1.4 模块划分

2. SpringSecurity 入门案例

2.1 创建一个项目

2.2 运行这个项目

2.3 权限管理中的相关概念

2.3.1主体(principal):

2.3.2认证(authentication)

2.3.3授权(authorization)

2.4 SpringSecurity 基本原理

 2.5 UserDetailsService接口:查询数据库用户名和密码的过程

2.6 PasswordEncoder 接口:数据加密接口

总结:

 2.7 SpringBoot对Security的自动配置

3. SpringSecurity Web权限方案

3.1 设置登录系统的账号、密码

3.2 实现数据库认证来完成用户登录

3.2.1 准备sql

3.2.2 添加相关依赖

3.2.3创建users表对应的实体类

3.2.4 整合MybatisPlus制作mapper

3.2.5在MyUserDetailsService调用mapper里面的方法查询数据库进行用户认证

 3.2.6在启动类上面添加@MapperScan注解

 3.2.7配置文件添加数据库配置

 3.2.8 测试访问

3.3自定义设置登录页面,不需要认证可以访问

3.3.1在配置类实现相关配置

3.4 基于角色或权限进行访问控制

3.4.1 hasAuthority 方法

3.4.2 hasAnyAuthority 方法 

3.4.3 hasRole 方法

 3.4.4 hasAnyRole

 3.5 自定义 403没有权限访问 页面

3.6 注解使用

3.7.1 @Secured

 3.7.2 @PreAuthorize

3.7.3 @PostAuthorize

3.7.4 @PostFilter,方法返回数据进行过滤

3.7.5 @PreFilter,传入方法数据精心过滤

3.8 基于数据库的记住我

3.8.1 创建表

3.8.2 添加数据库的配置文件

3.8.3 编写配置类

3.8.4 修改安全配置类 

 3.8.5 页面添加记住我复选框

此处:name 属性值必须位 remember-me.不能改为其他值

3.8.6 进行登录测试

3.8.7 设置有效期

3.9 用户注销

3.9.1 在新建登录成功页面添加一个退出连接

3.9.2 在配置类中添加退出映射地址

3.10 CSRF

3.10.1 CSRF 理解

3.10.2 案例

3.10.3 Spring Security 实现 CSRF 的原理



                                                 

 

1. SpringSecurity 框架简介

1.1 概要

        Spring 是非常流行和成功的 Java 应用开发框架,Spring Security正是Spring家族中的成员。Spring Security 基于 Spring 框架,提供了一套 Web 应用安全性的完整解决方案。
       正如你可能知道的关于安全方面的两个主要区域是“认证”和“授权”(或者访问控制),一般来说,Web 应用的安全性包括用户认证(Authentication)和用户授权(Authorization)两个部分,这两点也是Spring Security重要核心功能。
   (1)用户认证指的是:验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统。用户认证一般要求用户提供用户名和密码。系统通过校验用户名和密码来完成认证过程。通俗点说就是系统认为用户是否能登录
    (2)用户授权指的是验证某个用户是否有权限执行某个操作。在一个系统中,不同用户所具有的权限是不同的。比如对一个文件来说,有的用户只能进行读取,而有的用户可以进行修改。一般来说,系统会为不同的用户分配不同的角色,而每个角色则对应一系列的权限。通俗点讲就是系统判断用户是否有权限去做某些事情

1.2 历史

“Spring Security开始于2003年年底,““spring的acegi安全系统”。 起因是Spring开发者邮件列表中的一个问题,有人提问是否考虑提供一个基于spring的安全实现。
        Spring Security 以“The Acegi Secutity System for Spring” 的名字始于2013年晚些时候。一个问题提交到Spring 开发者的邮件列表,询问是否已经有考虑一个机遇Spring 的安全性社区实现。那时候Spring 的社区相对较小(相对现在)。实际上Spring自己在2013年只是一个存在于ScourseForge的项目,这个问题的回答是一个值得研究的领域,虽然目前时间的缺乏组织了我们对它的探索。

       考虑到这一点,一个简单的安全实现建成但是并没有发布。几周后,Spring社区的其他成员询问了安全性,这次这个代码被发送给他们。其他几个请求也跟随而来。到2014年一月大约有20万人使用了这个代码。这些创业者的人提出一个SourceForge项目加入是为了,这是在2004三月正式成立。

       在早些时候,这个项目没有任何自己的验证模块,身份验证过程依赖于容器管理的安全性和Acegi安全性。而不是专注于授权。开始的时候这很适合,但是越来越多的用户请求额外的容器支持。容器特定的认证领域接口的基本限制变得清晰。还有一个相关的问题增加新的容器的路径,这是最终用户的困惑和错误配置的常见问题。
       Acegi安全特定的认证服务介绍。大约一年后,Acegi安全正式成为了Spring框架的子项目。1.0.0最终版本是出版于2006 -在超过两年半的大量生产的软件项目和数以百计的改进和积极利用社区的贡献。

     Acegi安全2007年底正式成为了Spring组合项目,更名为"Spring Security"。

1.3 同款产品对比

1.3.1 Spring Security

  Spring技术栈的组成部分。

通过提供完整可扩展的认证和授权支持保护你的应用程序。
https://spring.io/projects/spring-security

SpringSecurity特点:

  • 和Spring无缝整合。
  • 全面的权限控制。
  • 专门为Web开发而设计。
    • 旧版本不能脱离Web环境使用。
    • 新版本对整个框架进行了分层抽取,分成了核心模块和Web模块。单独引入核心模块就可以脱离Web环境。
  • 重量级。

 

1.3.2 Shiro

Apache旗下的轻量级权限控制框架。

特点:

  •  轻量级。Shiro主张的理念是把复杂的事情变简单。针对对性能有更高要求的互联网应用有更好表现。
  • 通用性。
    • 好处:不局限于Web环境,可以脱离Web环境使用。
    • 缺陷:在Web环境下一些特定的需求需要手动编写代码定制。

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

相对于 Shiro,在 SSM 中整合 Spring Security 都是比较麻烦的操作,所以,Spring Security 虽然功能比 Shiro 强大,但是使用反而没有 Shiro 多(Shiro 虽然功能没有 Spring Security 多,但是对于大部分项目而言,Shiro 也够用了)。

自从有了 Spring Boot 之后,Spring Boot 对于 Spring Security 提供了自动化配置方案,可以使用更少的配置来使用 Spring Security。

因此,一般来说,常见的安全管理技术栈的组合是这样的:

  • SSM + Shiro

  • Spring Boot/Spring Cloud + Spring Security

以上只是一个推荐的组合而已,如果单纯从技术上来说,无论怎么组合,都是可以运行的。

1.4 模块划分

2. SpringSecurity 入门案例

2.1 创建一个项目

修改pom.xml

修改启动端口:server.port=8111

新建TestController 测试

package com.atguigu.springsecuritydemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName TestController
 * @Description
 * @Author wangzhengguo
 * @Date 2020/11/3 9:15
 **/
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("hello")
    public String add() {
        return "hello security";
    }
}

2.2 运行这个项目

访问localhost:8111/test/hello

默认的用户名:user


密码在项目启动的时候在控制台会打印,注意每次启动的时候密码都回发生变化! 

 输入用户名,密码,这样表示可以访问了

2.3 权限管理中的相关概念

2.3.1主体(principal):

principal:使用系统的用户或设备或从其他系统远程登录的用户等等。简单说就是谁使用系统谁就是主体

2.3.2认证(authentication)

权限管理系统确认一个主体的身份,允许主体进入系统。简单说就是“主体”证明自己是谁。

笼统的认为就是以前所做的登录操作。

2.3.3授权(authorization)

将操作系统的“权力”“授予”“主体”,这样主体就具备了操作系统中特定功能的能力。

所以简单来说,授权就是给用户分配权限。

2.4 SpringSecurity 基本原理

SpringSecurity 本质是一个过滤器链.

从启动是可以获取到过滤器链:

org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter
org.springframework.security.web.context.SecurityContextPersistenceFilter
org.springframework.security.web.header.HeaderWriterFilter
org.springframework.security.web.csrf.CsrfFilter
org.springframework.security.web.authentication.logout.LogoutFilter
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter
org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter
org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter
org.springframework.security.web.savedrequest.RequestCacheAwareFilter
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter
org.springframework.security.web.authentication.AnonymousAuthenticationFilter
org.springframework.security.web.session.SessionManagementFilter
org.springframework.security.web.access.ExceptionTranslationFilter
org.springframework.security.web.access.intercept.FilterSecurityInterceptor

代码底层流程:重点看三个过滤器:

  1. FilterSecurityInterceptor:是一个方法级的权限过滤器, 基本位于过滤链的最底部。通过查看FilterSecurityInterceptor.class的源码:

     super.beforeInvocation(fi) 表示查看之前的filter 是否通过。

    fi.getChain().doFilter(fi.getRequest(), fi.getResponse());表示真正的调用后台的服务。

  2. ExceptionTranslationFilter:是个异常过滤器,用来处理在认证授权过程中抛出的异常。通过查看ExceptionTranslationFilter.class的源码:

  3. UsernamePasswordAuthenticationFilter :对/login的POST请求做拦截,校验表单中用户名,密码。通过查看UsernamePasswordAuthenticationFilter .class的源码:

 2.5 UserDetailsService接口:查询数据库用户名和密码的过程

当什么也没有配置的时候,账号和密码是由Spring Security定义生成的。而在实际项目中账号和密码都是从数据库中查询出来的。 所以我们要通过自定义逻辑控制认证逻辑。

如果需要自定义逻辑时,只需要实现UserDetailsService接口即可。接口定义如下:

          ⚫ 返回值UserDetails,其源码如下:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.userdetails;

import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;

public interface UserDetails extends Serializable {
    // 表示获取登录用户所有权限
    Collection<? extends GrantedAuthority> getAuthorities();

    // 表示获取密码
    String getPassword();

    // 表示获取用户名
    String getUsername();

    // 表示判断账户是否过期
    boolean isAccountNonExpired();

    // 表示判断账户是否被锁定
    boolean isAccountNonLocked();

    // 表示凭证{密码}是否过期
    boolean isCredentialsNonExpired();

    // 表示当前用户是否可用
    boolean isEnabled();
}

这个类是系统默认的用户“主体

以下是UserDetails实现类:在idea中快捷键CTRL+H查看类的继承关系图

以后我们只需要使用User 这个实体类即可! 

      ⚫ 方法参数 username

表示用户名。此值是客户端表单传递过来的数据。默认情况下必须叫username,否则无法接收。

2.6 PasswordEncoder 接口:数据加密接口

源码如下:


 

 // 表示把参数按照特定的解析规则进行解析
String encode(CharSequence rawPassword); 

// 表示验证从存储中获取的编码密码与编码后提交的原始密码是否匹配。如果密码匹配,则返回true;如果不匹配,则返回false。第一个参数表示需要被解析的密码。第二个参数表示存储的密码。 
boolean matches(CharSequence rawPassword, String encodedPassword); 

// 表示如果解析的密码能够再次进行解析且达到更安全的结果则返回true,否则返回false。默认返false。
default boolean upgradeEncoding(String encodedPassword) { 
    return false;
}

接口实现类:

  • BCryptPasswordEncoder是Spring Security官方推荐的密码解析器,平时多使用这个解析器。
  • BCryptPasswordEncoder是对bcrypt强散列方法的具体实现。是基于Hash算法实现的单向加密。可以通过strength控制加密强度,默认10. 

   ⚫ 查用方法演示

    @Test
    void test01() {
        // 创建密码解析器 
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        // 对密码进行加密 
        String atguigu = bCryptPasswordEncoder.encode("atguigu");
        // 打印加密之后的数据 
        System.out.println("加密之后数据:\t" + atguigu);
        //判断原字符加密后和加密之前是否匹配 
        boolean result = bCryptPasswordEncoder.matches("atguigu", atguigu); 
        // 打印比较结果
        System.out.println("比较结果:\t" + result);
    }

总结:

 2.7 SpringBoot对Security的自动配置

https://docs.spring.io/spring-security/site/docs/5.3.4.RELEASE/reference/html5/#servlet-hello

3. SpringSecurity Web权限方案

3.1 设置登录系统的账号、密码

  1. 第一种方式:通过配置文件
  2. 通过配置类
    package com.atguigu.springsecuritydemo.config;
    
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.crypto.password.PasswordEncoder;
    
    /**
     * @ClassName SecurityConfig
     * @Description  SpringSecurity Web权限方案
     *                  方式二:编写类实现接口,设置登录系统的账号、密码
     * @Author wangzhengguo
     * @Date 2020/11/3 12:28
     **/
    @Configuration
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            //加密密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode("123");
    
            auth.inMemoryAuthentication().withUser("lucy").password(password).roles();
        }
    
        /**
         * 默认没有PasswordEncoder对象,需要手动创建
         * @return
         */
        @Bean
        PasswordEncoder passwordEncoder(){
            return new BCryptPasswordEncoder();//new一个PasswordEncoder的实现类
        }
    }
    
  3. 自定义实现类设置

第一步:创建配置类,设置使用哪个UserDetailsService实现类

package com.atguigu.springsecuritydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @ClassName SecurityConfigBySelect
 * @Description SpringSecurity Web权限方案
 * 方式三:自定义编写实现类,设置登录系统的账号、密码,账号和密码是查询出来的
 * @Author wangzhengguo
 * @Date 2020/11/3 12:28
 **/
@Configuration
public class SecurityConfigBySelect extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 默认没有PasswordEncoder对象,需要手动创建
     *
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//new一个PasswordEncoder的实现类
    }
}

第二步:编写实现类,返回User对象,User对象有用户名密码和操作权限

package com.atguigu.springsecuritydemo.service;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName MyUserDetailsService
 * @Description 自定义UserDetailsService实现类
 * @Author wangzhengguo
 * @Date 2020/11/3 13:02
 **/
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");//模拟权限集合

        return new User("mary",new BCryptPasswordEncoder().encode("123"),auths);
    }
}

 

3.2 实现数据库认证来完成用户登录

查询数据库完成用户认证

*整合MyBatisPlus完成数据库操作

3.2.1 准备sql

create table users(
	id bigint primary key auto_increment,
	username varchar(20) unique not null,
	password varchar(100)
);
-- 密码atguigu
insert into users values(1,'张san','$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');
-- 密码atguigu
insert into users values(2,'李si','$2a$10$2R/M6iU3mCZt3ByG7kwYTeeW0w7/UqdeXrb27zkBIizBvAven0/na');
	create table role(
	id bigint primary key auto_increment,
	name varchar(20)
);
insert into role values(1,'管理员');
insert into role values(2,'普通用户');
create table role_user(
	uid bigint,
	rid bigint
);
insert into role_user values(1,1);
insert into role_user values(2,2);
create table menu(
	id bigint primary key auto_increment,
	name varchar(20),
	url varchar(100),
	parentid bigint,
	permission varchar(20)
);
insert into menu values(1,'系统管理','',0,'menu:system');
insert into menu values(2,'用户管理','',0,'menu:user');
create table role_menu(
	mid bigint,
	rid bigint
);
insert into role_menu values(1,1);
insert into role_menu values(2,1);
insert into role_menu values(2,2);

3.2.2 添加相关依赖

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--lombok用来简化实体类-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

3.2.3创建users表对应的实体类

package com.atguigu.springsecuritydemo.entity;

import lombok.Data;

/**
 * @ClassName Users
 * @Description
 * @Author wangzhengguo
 * @Date 2020/11/3 13:33
 **/
@Data
public class Users {
    private Integer id;
    private String username;
    private String password;
}

 

3.2.4 整合MybatisPlus制作mapper

package com.atguigu.springsecuritydemo.mapper;

import com.atguigu.springsecuritydemo.entity.Users;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

/**
 * @ClassName UsersMapper
 * @Description users的mapper接口层
 * @Author wangzhengguo
 * @Date 2020/11/3 13:36
 **/
@Repository//不加也可以,加了不让spring在注入时候爆红,看着不舒服,原因是UsersMapper是一个接口,实现类被mybatisplus封装了,spring不能识别
public interface UsersMapper extends BaseMapper<Users> {
}

3.2.5在MyUserDetailsService调用mapper里面的方法查询数据库进行用户认证

package com.atguigu.springsecuritydemo.service;

import com.atguigu.springsecuritydemo.entity.Users;
import com.atguigu.springsecuritydemo.mapper.UsersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @ClassName MyUserDetailsService
 * @Description 自定义UserDetailsService实现类
 * @Author wangzhengguo
 * @Date 2020/11/3 13:02
 **/
@Service("userDetailsService")
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UsersMapper usersMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //调用usersMapper方法查询数据库
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.ge("username", username);
        Users users = usersMapper.selectOne(wrapper);
        if (StringUtils.isEmpty(users)) {//数据库没有用户名,认证失败
            throw new UsernameNotFoundException("用户名不存在!");
        }
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList("role");//模拟权限集合

        return new User(users.getUsername(), new BCryptPasswordEncoder().encode(users.getPassword()), auths);
    }
}

 3.2.6在启动类上面添加@MapperScan注解

 

 3.2.7配置文件添加数据库配置

 3.2.8 测试访问

 

输入张san,atguigu,测试通过 

3.3自定义设置登录页面,不需要认证可以访问

3.3.1在配置类实现相关配置

package com.atguigu.springsecuritydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 *@ClassName SecurityConfigByWeb
 *@Description  自定义设置登录页,不需要认证可以访问
 *@Author wangzhengguo
 *@Date 2020-11-04 09:34:50
 **/
@Configuration
public class SecurityConfigByWeb extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    /**
     * 默认没有PasswordEncoder对象,需要手动创建
     *
     * @return
     */
    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();//new一个PasswordEncoder的实现类
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http.formLogin()//自定义自己编写的登录页面
                .loginPage("/login.html")//配置哪个 url 为登录页面,这里可以配置请求,也可以直接配置页面
                .loginProcessingUrl("/user/login")// 设置哪个是登录的 url。
                .defaultSuccessUrl("/test/index")//登录成功之后跳转到哪个 url
                .failureForwardUrl("/fail")// 登录失败之后跳转到哪个 url
                .permitAll()
                .and().authorizeRequests()
                .antMatchers("/","/test/hello","/user/login").permitAll()//设置哪些路径可以直接访问,不需要认证
                .anyRequest().authenticated()//表示所有请求都可以访问
                .and().csrf().disable();//关闭csrf防护
    }
}

3.3.2在添加controller方法

    @GetMapping("index")
    public String index() {
        return "hello index";
    }

3.3.1添加login.html页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/user/login" method="post">
        用户名:<input type="text" name="username">
        <br/>
        密码:<input type="text" name="password">
        <br/>
        <input type="submit" value="login">
    </form>
</body>
</html>



注意:页面提交方式必须为 post 请求,所以上面的页面不能使用,用户名,密码必须为 username,password

原因:

在执行登录的时候会走一个过滤器 UsernamePasswordAuthenticationFilter

如果修改配置可以调用 usernameParameter()和 passwordParameter()方法

 测试可以直接访问登录页面,登录成功,直接访问的页面不需要认证

3.4 基于角色或权限进行访问控制

3.4.1 hasAuthority 方法

如果当前的主体具有指定的权限,则返回 true,否则返回 false,该方法针对用户某一个权限时

⚫ 修改配置类,设置当前访问地址有哪些权限

⚫ 在UserDetailsService把返回User对象设置权限

没有权限时访问:admins和abc不匹配

有权限时候访问:admins和admins匹配

3.4.2 hasAnyAuthority 方法 

如果当前的主体有任何提供的角色(给定的作为一个逗号分隔的字符串列表)的话,返回 true.该方法针对用户多个权限时

hasAuthority 和 hasAnyAuthority 的底层实现

3.4.3 hasRole 方法

如果用户具备给定角色就允许访问,否则出现 403。

如果当前主体具有指定的角色,则返回 true。

 3.4.4 hasAnyRole

表示用户具备任何一个条件都可以访问。

hasRole 方法和hasAnyRole方法的源码:

注意配置文件中不需要添加”ROLE_“,因为底层代码会自动添加与之进行匹配

 3.5 自定义 403没有权限访问 页面

修改访问配置类

新建 unauth.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="https://help.fanruan.com/uploads/201810/154026091510U0KFFx.png">
</body>
</html>

测试: 

3.6 注解使用

3.7.1 @Secured

判断是否具有角色,另外需要注意的是这里匹配的字符串需要添加前缀“ROLE_“。

  1. 使用注解先要开启注解功能! @EnableGlobalMethodSecurity(securedEnabled=true),注解可以添加在启动类上面,也可以添加在权限配置类上
  2. 在控制器方法上添加注解
  3.  UserDetailsService设置用户角色

 3.7.2 @PreAuthorize

先开启注解功能: @EnableGlobalMethodSecurity(prePostEnabled = true)

@PreAuthorize:注解适合进入方法前的权限验证, @PreAuthorize 可以将登录用 户的 roles/permissions 参数传到方法中。

在controller的方法上面添加注解

 UserDetailsService设置用户角色

 

3.7.3 @PostAuthorize

先开启注解功能: @EnableGlobalMethodSecurity(prePostEnabled = true)

@PostAuthorize 注解使用并不多,在方法执行后再进行权限验证,适合验证带有返回值 的权限.

在controller的方法上面添加注解

 

UserDetailsService设置用户角色

3.7.4 @PostFilter,方法返回数据进行过滤

@PostFilter :权限验证之后对数据进行过滤

例:留下用户名是 admin1 的数据 表达式中的 filterObject 引用的是方法返回值 List 中的某一个元素

3.7.5 @PreFilter,传入方法数据精心过滤

@PreFilter: 进入控制器之前对数据进行过滤

 3.7.6 权限表达式

https://docs.spring.io/springsecurity/site/docs/5.3.4.RELEASE/reference/html5/#el-access

3.8 基于数据库的记住我

自动登录

  • cookie技术实现
  • 安全框架机制实现自动登录

实现原理:

3.8.1 创建表

CREATE TABLE `persistent_logins` (
 `username` varchar(64) NOT NULL,
 `series` varchar(64) NOT NULL,
 `token` varchar(64) NOT NULL,
 `last_used` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`series`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3.8.2 添加数据库的配置文件

3.8.3 编写配置类

package com.atguigu.springsecuritydemo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * @ClassName BrowserSecurityConfig
 * @Description 浏览器记住我功能的数据库实现
 * @Author wangzhengguo
 * @Date 2020/11/4 14:48
 **/
@Configuration
public class BrowserSecurityConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        // 赋值数据源
        jdbcTokenRepository.setDataSource(dataSource);
        // 自动创建表,第一次执行会创建,以后要执行就要删除掉!(建议手动创建)
        //jdbcTokenRepository.setCreateTableOnStartup(true);
        return jdbcTokenRepository;
    }
}

3.8.4 修改安全配置类 

 

 3.8.5 页面添加记住我复选框

此处:name 属性值必须位 remember-me.不能改为其他值

3.8.6 进行登录测试

登录成功之后,关闭浏览器再次访问 http://localhost:8111/getAll,发现依然可以使用!

3.8.7 设置有效期

默认 2 周时间。但是可以通过设置状态有效时间,即使项目重新启动下次也可以正常登 录。

在配置文件中设置

3.9 用户注销

3.9.1 在新建登录成功页面添加一个退出连接

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    登录成功!
    <a href="/logout">退出</a>
</body>
</html>

3.9.2 在配置类中添加退出映射地址

 测试:登录成功之后,到登录成功页面:

点击退出:

访问http://localhost:8111/test/index需要登录,成功测试退出之后,是无法访问需要登录时才能访问的控制器!

3.10 CSRF

3.10.1 CSRF 理解

跨站请求伪造(英语:Cross-site request forgery),也被称为 one-click attack 或者 session riding,通常缩写为 CSRF 或者 XSRF, 是一种挟制用户在当前已 登录的 Web 应用程序上执行非本意的操作的攻击方法。跟跨网站脚本(XSS)相比,XSS 利用的是用户对指定网站的信任,CSRF 利用的是网站对用户网页浏览器的信任。

跨站请求攻击,简单地说,是攻击者通过一些技术手段欺骗用户的浏览器去访问一个 自己曾经认证过的网站并运行一些操作(如发邮件,发消息,甚至财产操作如转账和购买 商品)。由于浏览器曾经认证过,所以被访问的网站会认为是真正的用户操作而去运行。 这利用了 web 中用户身份验证的一个漏洞:简单的身份验证只能保证请求发自某个用户的 浏览器,却不能保证请求本身是用户自愿发出的。

从 Spring Security 4.0 开始,默认情况下会启用 CSRF 保护,以防止 CSRF 攻击应用 程序,Spring Security CSRF 会针对 PATCH,POST,PUT 和 DELETE 方法进行防护。

3.10.2 案例

在登录页面添加一个隐藏域:

<input type="hidden" th:if="${_csrf}!=null" th:value="${_csrf.token}" name="_csrf"/>

关闭安全配置的类中的 csrf

3.10.3 Spring Security 实现 CSRF 的原理

  1. 生成 csrfToken 保存到 HttpSession 或者 Cookie 中。

SaveOnAccessCsrfToken 类有个接口 CsrfTokenRepository

 

当前接口实现类:HttpSessionCsrfTokenRepository,CookieCsrfTokenRepository

 

2. 请求到来时,从请求中提取 csrfToken,和保存的 csrfToken 做比较,进而判断当 前请求是否合法。主要通过 CsrfFilter 过滤器来完成。

 

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

java水泥工

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值