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)

大家都在看

  • 在VS code使用Remote-SSH远程连接Linux 开发C++ 配置详细介绍

    VS code 远程连接服务器,编译C++ 一、前期准备 1、VS code安装 Remote-SSH插件 2、Windows安装SSH。 3、Linux服务器连接测试。 a.接通…

    Linux 2023年5月27日
    0139
  • ssh远程连接服务

    TCP/22 SSH 应用层协议 作用:远程连接设备, 方便操作 1、本地管理方式 安装系统、故障修复 2、远程连接的方式 centos7.x版本中的ssh默认是开启的,所以查看一…

    Linux 2023年6月7日
    081
  • Redis主从复制的配置和实现原理

    Redis的持久化功能在一定程度上保证了数据的安全性,即便是服务器宕机的情况下,也可以保证数据的丢失非常少。通常,为了避免服务的单点故障,会把数据复制到多个副本放在不同的服务器上,…

    Linux 2023年5月28日
    077
  • MySQL-连接数据库

    连接数据库在操作数据库之前,需要连接它,输入命令:mysql -u用户名 -p密码。 在你自己本机上连接数据库用上述方式是可以的,不过在平台上连接数据库还需要加上一句-h127.0…

    Linux 2023年6月8日
    089
  • Tensorflow-逻辑斯蒂回归

    1.交叉熵 逻辑斯蒂回归这个模型采用的是交叉熵,通俗点理解交叉熵 推荐一篇文章讲的很清楚: 因此,交叉熵越低,这个策略就越好,最低的交叉熵也就是使用了真实分布所计算出来的信息熵,因…

    Linux 2023年6月6日
    079
  • 学习一下 JVM (三) — 了解一下 垃圾回收

    一、简单了解几个概念 1、什么是垃圾(Garbage)?什么是垃圾回收(Garbage Collection,简称 GC)? (1)什么是垃圾(Garbage)?这里的垃圾 指的是…

    Linux 2023年6月11日
    093
  • 模型层

    准备阶段 django自带的sqlite3数据库,功能很少,并且针对日期类型不精确 准备步骤 数据库正向迁移命令(将类操作映射到表中) python3 manage.py make…

    Linux 2023年6月7日
    088
  • SQL55 分页查询employees表,每5行一页,返回第2页的数据

    LIMIT子句 本题链接表结构如下所示。 +——–+————+——&#8…

    Linux 2023年6月13日
    081
  • 【原创】Linux虚拟化KVM-Qemu分析(一)

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

    Linux 2023年6月8日
    089
  • Linux特殊权限之suid、sgid、sbit权限

    文件权限管理之特殊命令 一:特殊权限 昨天所学的Linux基本权限为为9个;分别是rwx rwx rwx。但有时会发现系统中会有一些特殊的权限位符号; 例如: Linux系统一共有…

    Linux 2023年5月27日
    0126
  • macOS Catalina new Shell,解决 The default interactive shell is now zsh

    The default interactive shell is now zsh. To update your account to use zsh, please run ch…

    Linux 2023年5月28日
    0132
  • Xshell小技巧

    鼠标右键粘贴 工具->选项->鼠标->向右按钮->(paste the clipboard contents.) 选定文本自动复制到剪贴板 工具->选…

    Linux 2023年5月28日
    0104
  • MIT6.828(Step0)——实验环境配置

    实验环境配置 VirtualBox虚拟机为载体,安装Ubuntu $ uname -a Linux eliot-VirtualBox 5.11.0-36-generic #40~2…

    Linux 2023年5月27日
    087
  • Java基础系列–02_运算符和程序的语句

    运算符:(1)算术运算符:+,-,*,/,%,++,–(加、减、乘、除、取余、自增,自减)++和–的注意事项:a:他们的作用是自增或者自减b:使用1.单独使…

    Linux 2023年6月7日
    085
  • 查询windows日志

    系统日志可以用来查看系统的一些信息,比如警告、错误、验证、开关机等。 打开系统日志 按下快捷键 win+R,输入 eventvwr.exe,并点击确定 查询开关机记录 点击左侧 W…

    Linux 2023年6月8日
    0103
  • Redis从入门到精通:中级篇

    原文链接:http://www.cnblogs.com/xrq730/p/8944539.html,转载请注明出处,谢谢 本文目录 上一篇文章以认识Redis为主,写了Redis系…

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