Security-权限

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS MySQL Serverless 高可用系列,价值2615元额度,1个月
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: -

介绍

原本配置折磨,springboot整合十分轻松,登陆,权限,还能网络安全

体验

创建springboot项目

导入依赖

<dependency>

 <groupId>org.springframework.boot</groupId>

 <artifactId>spring-boot-starter-security</artifactId>

</dependency>

实现controller

@RestController

   public class HelloSecurity {


       @RequestMapping("/hello")

       public String hello(){

           return "hello security";

       }

   }

登陆验证

当你使用http://localhost:8080/hello会重定向到http://localhost:8080/login

登录

随机生成密码

默认用户名:user

密码:

yaml自定义密码

spring:

datasource:

driver-class-name: com.mysql.cj.jdbc.Driver

url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC

username: root

password: 123456

security:

user:

  name: root

  password: root

代码类config设置

首先config配置

/**

* @author 伍六七

* @date 2022/9/7 12:22

*/

@Configuration

public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {

   /**

    * 添加认证

    * withUser--添加用户

    * password--设置密码

    * roles--设置能访问的请求路径

    * @param auth

    * @throws Exception

    */

   @Override

   protected void configure(AuthenticationManagerBuilder auth) throws Exception {

       auth.inMemoryAuthentication()

               .withUser("admin")//添加用户admin

               .password("{noop}admin")// 不设置密码加密

               .roles("ADMIN","USER")// 添加角色为admin,user

               .and()

               .withUser("user")

               .password("{noop}user")

               .roles("USER")

               .and()

               .withUser("tmp")

               .password("{noop}tmp")

               .roles();

   }


   /**

    * 添加权限

    * .antMatchers("/product/**").hasRole("USER")

    * 能访问的请求需要什么角色的权限

    * @param http

    * @throws Exception

    */

   @Override

   protected void configure(HttpSecurity http) throws Exception {

       http

               .authorizeRequests()

               .antMatchers("/product/**").hasRole("USER")//添加/product/** 下的所有请求只能由user角色才能访问

               .antMatchers("/admin/**").hasRole("ADMIN")//添加/admin/** 下的所有请求只能由admin角色才能访问

               .anyRequest().authenticated()// 没有定义的请求,所有的角色都可以访问(tmp也可以)。

               .and()

               .formLogin().and()

               .httpBasic();

   }

}


按照不同权限的路径去设置请求

/**

* 需要管理员权限

* @author 伍六七

* @date 2022/9/7 12:41

*/

@RestController

@RequestMapping("/admin")

public class AdminController {

   @RequestMapping("/hello")

   public String hello(){

       return "THIS IS ADMIN HTML!";

   }

}


/**

* 需要用户权限

* @author 伍六七

* @date 2022/9/7 12:41

*/

@RestController

@RequestMapping("/product")

public class ProductController {

   @RequestMapping("/hello")

   public String hello(){

       return "hTHIS IS PRODUCT HTML!";

   }

}


/**

* 所有权限即可

* @author 伍六七

* @date 2022/9/7 10:41

*/

@RestController

public class HelloSecurity {


   @RequestMapping("/hello")

   public String hello(){

       return "hello security";

   }

}

通过上面的设置,访问http://localhost:8080/admin/hello只能由admin访问,http://localhost:8080/product/hello admin和user都可以访问,http://localhost:8080/hello 所有用户(包括tmp)都可以访问。

使用数据库的用户名、密码登录

建表

默认角色前缀必须是ROLE_,因为spring-security会在授权的时候自动使用match中的角色加上ROLE_后进行比较。

CREATE TABLE `users` (

 `id` int(28) NOT NULL,

 `login` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,

 `password` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,

 `role` varchar(255) COLLATE utf8mb4_general_ci DEFAULT NULL,

 PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT INTO `users`(`id`, `login`, `password`, `role`) VALUES (1, 'user', 'user', 'ROLE_USER');

INSERT INTO `users`(`id`, `login`, `password`, `role`) VALUES (2, 'admin', 'admin', 'ROLE_ADMIN');

添加依赖

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

   <groupId>mysql</groupId>

   <artifactId>mysql-connector-java</artifactId>

</dependency>

添加yaml配置

spring:

datasource:

driver-class-name: com.mysql.cj.jdbc.Driver

url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC

username: root

password: 123456


配置config类

/**

* @author 伍六七

* @date 2022/9/7 13:16

*/

@Configuration

public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {


   @Autowired

   private UserDetailsService userDetailsService;


   @Override

   protected void configure(AuthenticationManagerBuilder auth) throws Exception {

       auth.userDetailsService(userDetailsService)//设置自定义userDetailsServiceImpl

           .passwordEncoder(passwordEncoder());

   }


   @Override

   protected void configure(HttpSecurity http) throws Exception {

       http.authorizeRequests()

           .antMatchers("/product/**").hasRole("USER")

           .antMatchers("/admin/**").hasRole("ADMIN")

           .anyRequest().authenticated()

           .and()

           .formLogin()

           .and()

           .httpBasic()

           .and()

           .logout().logoutUrl("/logout");

   }


   @Bean

   public PasswordEncoder passwordEncoder() {

       return NoOpPasswordEncoder.getInstance();// 使用不使用加密算法保持密码

       //        return new BCryptPasswordEncoder();

   }

}

加密

/**

*加密

*/

@Test

void encode(){

   BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

   String password = bCryptPasswordEncoder.encode("user");

   String password2 = bCryptPasswordEncoder.encode("admin");

   System.out.println(password);

   System.out.println(password2);

}


UserDetailsService-验证

调用UserDetailsService的实现类去查找用户

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
API iOS开发
iOS面试关于runtime
iOS面试关于runtime
223 0
|
7月前
|
人工智能 机器人 开发工具
LazyLLM:还在为AI应用开发掉头发?商汤开源智能体低代码开发工具,三行代码部署聊天机器人
LazyLLM 是一个低代码开发平台,可帮助开发者快速构建多智能体大语言模型应用,支持一键部署、跨平台操作和多种复杂功能。
279 3
|
9月前
|
机器学习/深度学习 存储 人工智能
《智领未来:C++ 与遗传算法在 AI 模型参数优化中的深度融合》
本文探讨了在C++中实现遗传算法并应用于人工智能模型参数优化的方法。遗传算法模拟自然界的进化过程,通过选择、交叉和变异等操作优化模型参数。文章详细介绍了C++实现遗传算法的关键步骤,包括定义个体与种群、初始化种群、适应度评估、选择、交叉、变异及迭代更新种群。此外,还讨论了C++实现遗传算法的优势与挑战,并展望了其在深度学习、强化学习、边缘计算等领域的应用前景。
216 9
|
8月前
|
存储 数据采集 Cloud Native
极速数仓ClickHouse步入云原生新纪元
极速数仓ClickHouse步入云原生新纪元,由ClickHouse核心研发团队技术总监王鹏程及长桥航行服务架构负责人刘文全主讲。内容涵盖ClickHouse的优势与应用场景、架构解析、最佳实践及未来展望。特别介绍了ClickHouse Enterprise版本在阿里云上的优化与创新,支持实时查询、高性能资源利用和丰富的SQL扩展。长桥证券分享了其基于阿里云ClickHouse构建行情服务的实践经验,展示了如何通过ClickHouse实现高效的数据存储与处理,显著降低存储成本并提升写入性能。
199 0
|
机器学习/深度学习 人工智能 数据可视化
【2024美国大学生数学建模竞赛】2024美赛C题网球运动中的势头,网球教练4.0没人比我更懂这个题了!!!
本文是一位自称对网球规则和比赛数据非常熟悉的计算机博士对2024美国大学生数学建模竞赛C题"网球运动中的势头"的全面解析,包括问题分析、数学模型构建、代码实现,以及完整论文的逐步更新过程。
249 1
【2024美国大学生数学建模竞赛】2024美赛C题网球运动中的势头,网球教练4.0没人比我更懂这个题了!!!
|
存储 算法 大数据
小米教你:2GB内存搞定20亿数据的高效算法
你好,我是小米。本文介绍如何在2GB内存中找出20亿个整数里出现次数最多的数。通过将数据用哈希函数分至16个小文件,每份独立计数后选出频次最高的数,最终比对得出结果。这种方法有效解决大数据下的内存限制问题,并可应用于更广泛的场景。欢迎关注我的公众号“软件求生”,获取更多技术分享!
331 12
靠这三步就能排查CPU占用100%?
靠这三步就能排查CPU占用100%?
464 0
|
Cloud Native Java 关系型数据库
阿里云 PolarDB-X 团队25届实习生招聘
阿里云 PolarDB-X 团队25届实习生招聘
|
运维 Dubbo Cloud Native
APISIX+Dubbo+Nacos 最佳实践
虽然使用 APISIX+Dubbo+Nacos,能够解决这个实践中最主要的两个问题。但是它在使用中仍然还有需要进步的地方。社区中会在后续的计划和展望中继续优化。
578 82
APISIX+Dubbo+Nacos 最佳实践
|
SQL 存储 关系型数据库
小知识随手记:使用Navicat进行数据库表设计
小知识随手记:使用Navicat进行数据库表设计
小知识随手记:使用Navicat进行数据库表设计