SpringSecurity 新版2.7以上 快速入门

SpringSecurity

快速入门

1、导入依赖


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

2、测试三种权限

2.7以前的版本

package com.mhy.security.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 OldSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //请求的规则
        http.authorizeHttpRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/level1/**").hasRole("vip1")
                .antMatchers("/level2/**").hasRole("vip2")
                .antMatchers("/level3/**").hasRole("vip3");

        // 没有权限跳到login页
        http.formLogin();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("shuisanya").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
                .and()
                .withUser("haha").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3");

    }
}

2.7以后的版本

package com.mhy.security.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class NewSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // @formatter:off
//        http
//                .authorizeHttpRequests()
//                .antMatchers("/").permitAll()
//                .antMatchers("/level1/**").hasRole("vip1")
//                .antMatchers("/level2/**").hasRole("vip2")
//                .antMatchers("/level3/**").hasRole("vip3");

        http.authorizeHttpRequests((authorize) -> {
            authorize.antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1")
                    .antMatchers("/level2/**").hasRole("vip2")
                    .antMatchers("/level3/**").hasRole("vip3");
        });

        http.formLogin();
        // @formatter:on
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user1 = User.withDefaultPasswordEncoder()
                                .username("shuisanya")
                                .password("123456")
                                .roles("vip1","vip2","vip3")
                                .build();
        UserDetails user2 = User.withDefaultPasswordEncoder()
                                .username("root")
                                .password("123456")
                                .roles("vip2","vip3")
                                .build();
        UserDetails user3 = User.withDefaultPasswordEncoder()
                                .username("haha")
                                .password("123456")
                                .roles("vip1")
                                .build();
        return new InMemoryUserDetailsManager(user1,user2,user3);
    }
}

3、测试自己设置加密

@Bean
public UserDetailsService userDetailsService() {
    UserDetails userDetails = User.withUsername("123456")
        .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
        .password("123456")
        .roles("vip2")
        .build();
    UserDetails user1 = User.withUsername("shuisanya")
        .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
        .password("123456")
        .roles("vip1","vip2","vip3")
        .build();
    UserDetails user2 = User.withUsername("root")
        .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
        .password("123456")
        .roles("vip2","vip3")
        .build();
    UserDetails user3 = User.withUsername("haha")
        .passwordEncoder(new Pbkdf2PasswordEncoder()::encode)
        .password("123456")
        .roles("vip1")
        .build();
    return new InMemoryUserDetailsManager(userDetails,user1,user2,user3);
}

@Bean
public PasswordEncoder passwordEncoder(){
    return new Pbkdf2PasswordEncoder();
}

连接数据库使用

导入依赖,这里使用mybatisPlus


     mysql
     mysql-connector-java

     com.baomidou
     mybatis-plus-boot-starter
     3.5.2

编写配置文件

spring.thymeleaf.cache=false

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456

配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
开启逻辑删除
mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=1
mybatis-plus.global-config.db-config.logic-not-delete-value=0

实现UserDetailsService接口的编写

@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserMapper userMapper;
    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        com.mhy.security.pojo.User user = userMapper.selectOne(wrapper);

        if (user == null){
            throw new UsernameNotFoundException("该用户不存在!");
        }

        List vip2 = AuthorityUtils.commaSeparatedStringToAuthorityList("vip2"); //权限 一般是从数据库来实现

        return new User(username,PasswordEncoderUtils.encode(user.getPassword()),vip2);
}

三种授权的配置

三种授权的配置

首页

SpringSecurity 新版2.7以上 快速入门

第一种 hasAuthority

这个参数只能配置一种授权

场景:

  • 访问/level1/**这个下面的所有只能是vip1才可以访问
  • 访问/level2/**这个下面的所有只能是vip2才可以访问
  • 访问/level3/**这个下面的所有只能是vip3才可以访问
@EnableWebSecurity
@Configuration
public class NewSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasAuthority("vip1")
                    .antMatchers("/level2/**").hasAuthority("vip2")
                    .antMatchers("/level3/**").hasAuthority("vip3");
        });

        http
                .formLogin() //开启登入功能
                .loginPage("/toLogin") //开启等去去的页面,去自己的页面
                .loginProcessingUrl("/login"); //登录请求的方法,这个是spring security帮你做

        http.csrf().disable(); //关闭csrf防火墙

        http.logout().logoutSuccessUrl("/"); //退出登录的页面

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }

}

第二种 hasRole

这个参数只能配置一种授权,但它会默认给你配置的授权名称前加一个 ROLE_

AuthorityAuthorizationManager类中的源码

private static final String ROLE_PREFIX = "ROLE_";
public static  AuthorityAuthorizationManager hasRole(String role) {
    Assert.notNull(role, "role cannot be null");
    return hasAuthority(ROLE_PREFIX + role);
}

场景:

  • 访问/level1/**这个下面的所有只能是vip1才可以访问
  • 访问/level2/**这个下面的所有只能是vip2才可以访问
  • 访问/level3/**这个下面的所有只能是vip3才可以访问

配置类

@EnableWebSecurity
@Configuration
public class NewSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasRole("vip1") // 这里实际上是ROLE_vip1
                    .antMatchers("/level2/**").hasRole("vip2") // 这里实际上是ROLE_vip1
                    .antMatchers("/level3/**").hasRole("vip3");// 这里实际上是ROLE_vip3
        });
        http
                .formLogin() //开启登入功能
                .loginPage("/toLogin") //开启等去去的页面,去自己的页面
                .loginProcessingUrl("/login"); //登录请求的方法,这个是spring security帮你做

        http.csrf().disable(); //关闭csrf防火墙

        http.logout().logoutSuccessUrl("/"); //退出登录的页面

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }

}

使用在编写实现UserDetailsService时候需要注意

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
com.mhy.security.pojo.User user = userMapper.selectOne(wrapper);
if (user == null){
throw new UsernameNotFoundException("该用户不存在!");
}

List vip2 = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_vip2");  //注意

return new User(username,PasswordEncoderUtils.encode(user.getPassword()),vip2);
}

第三种 hasAnyAuthority

配置多个参数

场景:

  • 访问/level1/**这个下面的所有是vip1才可以访问
  • 访问/level2/**这个下面的所有是vip1,vip2才可以访问
  • 访问/level3/**这个下面的所有是vip1,vip2,vip3才可以访问

配置类:

@EnableWebSecurity
@Configuration
public class NewSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasAnyAuthority("vip1","vip2","vip3")
                    .antMatchers("/level2/**").hasAnyAuthority("vip2","vip3")
                    .antMatchers("/level3/**").hasAnyAuthority("vip3");
        });

        http
                .formLogin() //开启登入功能
                .loginPage("/toLogin") //开启等去去的页面,去自己的页面
                .loginProcessingUrl("/login"); //登录请求的方法,这个是spring security帮你做

        http.csrf().disable(); //关闭csrf防火墙
        http.logout().logoutSuccessUrl("/"); //退出登录的页面
        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }
}

第四种 hasAnyAuthority

配置多个参数

这个参数只能配置一种授权,但它会默认给你配置的授权名称前加一个 ROLE_

场景:

  • 访问/level1/**这个下面的所有是vip1才可以访问
  • 访问/level2/**这个下面的所有是vip1,vip2才可以访问
  • 访问/level3/**这个下面的所有是vip1,vip2,vip3才可以访问

配置类

@EnableWebSecurity
@Configuration
public class NewSecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> {
            authorize
                    .antMatchers("/").permitAll()
                    .antMatchers("/level1/**").hasAnyRole("vip1","vip2","vip3")
                    .antMatchers("/level2/**").hasAnyRole("vip2","vip3")
                    .antMatchers("/level3/**").hasAnyRole("vip3");
        });

        http
                .formLogin() //开启登入功能
                .loginPage("/toLogin") //开启等去去的页面,去自己的页面
                .loginProcessingUrl("/login"); //登录请求的方法,这个是spring security帮你做

        http.csrf().disable(); //关闭csrf防火墙

        http.logout().logoutSuccessUrl("/"); //退出登录的页面

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new Pbkdf2PasswordEncoder();
    }
}

Original: https://www.cnblogs.com/shuisanya/p/16601911.html
Author: 水三丫
Title: SpringSecurity 新版2.7以上 快速入门

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

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

(0)

大家都在看

  • Go实现安全双检锁的方法和最佳实践

    不安全的双检锁 从其他语言转入Go语言的同学经常会陷入一个思考:如何创建一个单例? 有些同学可能会把其它语言中的双检锁模式移植过来,双检锁模式也称为懒汉模式,首次用到的时候才创建实…

    Linux 2023年6月13日
    096
  • 数据结构 二叉树

    cpp;gutter:true;</p> <h1>include</h1> <p>using namespace std;</…

    Linux 2023年6月13日
    084
  • HTTP状态码1XX深入理解

    前段时间看了《御赐小仵作》,里面有很多细节很有心。看了一些评论都是:终于在剧里能够看到真正在搞事业、发了工资第一时间还钱的正常人了。我印象比较深的是王府才能吃上的葡萄。觉得非常合理…

    Linux 2023年6月13日
    0102
  • 【原创】Linux PCI驱动框架分析(二)

    背 景 Read the fucking source code! –By 鲁迅 A picture is worth a thousand words. &#8211…

    Linux 2023年6月8日
    0107
  • Redis进阶 事务:Redis事务详解

    Redis事务相关命令 Redis事务执行步骤 Redis 事务的本质是一组命令的集合。事务支持一次执行多个命令,一个事务中所有命令都会被序列化。在事务执行过程,会按照顺序串行化执…

    Linux 2023年5月28日
    0100
  • 软件测试基础理论

    软件基础的理论 一, 什么是软件产品 它是一个逻辑产品,没有实体,包括程序,文档和数据,需要通过终端设备才能体现出来功能和作用 二, 软件产品的中间过程文档 客户需求 &#…

    Linux 2023年6月7日
    088
  • Kafka部署安装及简单使用

    一、环境准备 1、jdk 8+ 2、zookeeper 3、kafka 说明:在kafka较新版本中已经集成了zookeeper,所以不用单独安装zookeeper,只需要在kaf…

    Linux 2023年6月13日
    0121
  • IDEA生成带参数和返回值注释

    步骤说明 打开IDEA进入点击左上角 – 文件 – 设置 – 编辑器 – 活动模板 新建活动模板 填写模板文本 编辑变量 添加变量表…

    Linux 2023年6月6日
    0110
  • js学习笔记——条件 循环

    今天发现之前学的爱前端的课中JS部分函数等不全,果断换了一个课——渡一的《Web前端开发JavaScript高薪课堂》接着学习,不过废话有点多 语法:1、单if,条件成立,执行语句…

    Linux 2023年6月13日
    074
  • ThinkPHP5 远程命令执行漏洞

    一、ThinkPHP介绍 轻量级框架,内部OOP和面向过程代码都存在,是国人自己开发的框架。ThinkPHP是一个快速、兼容而且简单的轻量级国产PHP开发框架,诞生于2006年初,…

    Linux 2023年6月14日
    080
  • node-java的使用及源码分析

    上篇文章简单提了下node调用java的方法但也只属于基本提了下怎么输出helloworld的层度,这次将提供一些案例和源码分析让我们更好地了解如何使用node-java库。 前置…

    Linux 2023年6月14日
    0104
  • 分析redis key大小的几种方法

    当redis被用作缓存时,有时我们希望了解key的大小分布,或者想知道哪些key占的空间比较大。本文提供了几种方法。 一. bigKeys 这是redis-cli自带的一个命令。对…

    Linux 2023年5月28日
    0137
  • 搭建部署Docker

    Docker安装准备: 首先看下服务器是否有旧版本,如果有需要卸载并且安装依赖 然后下载docker仓库repo源: 安装完成后查看docker仓库版本信息: yum安装docke…

    Linux 2023年6月8日
    0110
  • django学习__1

    Django python网络编程回顾 之前我们介绍过web应用程序和http协议,简单了解过web开发的概念。Web应用程序的本质 接收并解析HTTP请求,获取具体的请求信息 处…

    Linux 2023年6月7日
    0106
  • 如何在Windows 10 上定时备份线上Minio 资源

    @ 一、系统环境 二、软件安装 三、设置定时任务 3.1 创建账号 3.2 同步测试 3.3 编写同步脚本 3.4 脚本测试 3.5 创建定时任务 3.6 定时任务测试 四、总结 …

    Linux 2023年5月27日
    0187
  • mit 6.824 lab2B,raft日志复制(lab2D中有关于此处大量代码修改找出了很多错误)

    lab2 说明: https://pdos.csail.mit.edu/6.824/labs/lab-raft.html 参考博客: https://zhuanlan.zhihu….

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