• SpringBoot整合SpringSecurity


    活动地址:CSDN21天学习挑战赛

    目前Spring官网给出的Security的最新版本为5.7.2,所以这里也以最新版作为整合,SpringBoot采用2.7.2版本.

    引入依赖

      <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-actuatorartifactId>
        dependency>
        
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-securityartifactId>
        dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    配置类

    注意点: 最新版Security 官方已经决定淘汰SpringSecurityConfigurationAdapter,也就是说最新版配置不需要再继承WebSecurityConfigurerAdapter这个类做配置,取而代之的是配置相应的过滤器链来进行相关配置, 配置方式以及属性保持不变.

    Security认证方式有两种: 基于内存的方式和基于数据库的方式;

    基于内存

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http.formLogin(form->{
                // 指定登录成功默认跳转url 
                form.defaultSuccessUrl("/hello");
                //这里有两个登陆成功路径跳转 下面这个见名知意,登录成功后请求转发,url并不会改变,并且     		 为post请求,需要注意.而上面则是Url重定向.根据实际需求选用即可.
                //form.successForwardUrl("/hello");
            });
            // 开启"记住我"功能
            http.rememberMe();
            //禁用缓存
            http.headers().cacheControl();
            return http.build();
        }
    
        @Bean
        public UserDetailsService userDetailsService(){
            UserDetails user = User.builder()
                    .username("demo")
                    .password(new BCryptPasswordEncoder().encode("123"))
                    .roles("USER")
                    .build();
             // 采用内存模式     
            return new InMemoryUserDetailsManager(user);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    之前版本配置方式对比

    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
                    .withUser("demo")
                    .password(passwordEncoder().encode("123"))
                    .authorities("123","ROLE_ADMIN");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    完成配置重启项目,观察启动日志,可以看到由于手动配置了账户密码,Spring已经不再打印默认的密码,并且登录页较之前多了一个Remember me的勾选框,说明配置类成功.
    在这里插入图片描述
    登录成功后,成功跳转
    在这里插入图片描述

    基于数据库JDBC

    与之前用法相同, 实现UserDetailsService接口即可,这里我模拟了一下数据库的查询,实际操作中替换即可.

    @Slf4j
    @Service
    public class UserService implements UserDetailsService {
    
        public HashMap dbMap = new HashMap();
        public void setDbMap(){
            ArrayList<GrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
            dbMap.put("demo",new User("demo",new BCryptPasswordEncoder().encode("123"),authorities));
            dbMap.put("cat",new User("cat",new BCryptPasswordEncoder().encode("321"),authorities));
            dbMap.put("tom",new User("tom",new BCryptPasswordEncoder().encode("456"),authorities));
        }
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            setDbMap();
            return (UserDetails) dbMap.get(username);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    相应的基于内存方式需要注释掉
    在这里插入图片描述
    同时添加登陆成功后相应的Handler,可以选择将用户不敏感信息,组装Token进行返回.
    在这里插入图片描述
    自此SpringBoot可以正常使用Security.

    需要其他配置可以看下这个博客,根据需要重即可 SpringSecurity认证流程

  • 相关阅读:
    [单片机框架][bsp层][N32G4FR][bsp_pwm] pwm配置和使用
    【leetcode面试经典150题】74. 填充每个节点的下一个右侧节点指针 II(C++)
    Win10如何删除登录账号?Win10删除登录账号的方法
    pyautogui 和pynput学习总结
    浅析-ES6
    JavaScript的垃圾回收机制
    【LeetCode】206. 反转链表
    lwip_nat
    如何使用 edu 邮箱注册 Azure
    vue2中,vue-easytable组件的使用(三)——实现表格的虚拟滚动功能
  • 原文地址:https://blog.csdn.net/qq_39236265/article/details/126198308