Security-权限

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群版 2核4GB 100GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用版 2核4GB 50GB
简介: -

介绍

原本配置折磨,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的实现类去查找用户

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
7月前
|
安全
/etc/security/cacerts 只读权限
/etc/security/cacerts 只读权限
223 0
|
Java Spring
5-SpringSecurity:RBAC及方法授权
5-SpringSecurity:RBAC及方法授权
324 0
5-SpringSecurity:RBAC及方法授权
|
1月前
|
安全 数据安全/隐私保护
security权限管理详解
security权限管理详解
|
10月前
|
安全 Java 数据库
Security授权实现
Security授权实现
42 0
|
安全 数据安全/隐私保护
JeeSite 访问控制权限
JeeSite 访问控制权限
173 0
|
安全 Java 数据安全/隐私保护
Spring Security-内置访问控制方法介绍和角色权限判断
Spring Security-内置访问控制方法介绍和角色权限判断
Spring Security-内置访问控制方法介绍和角色权限判断
|
XML 移动开发 安全
Spring Security实现权限管理(用户、角色、权限)
Spring Security实现权限管理(用户、角色、权限)
581 0
|
存储 算法 前端开发
Security+Oauth2权限认证(案例 源码)
Security+Oauth2权限认证(案例 源码)
129 0
Security+Oauth2权限认证(案例 源码)
|
Java Apache Maven
Shiro--从一个简单的 Realm 开始权限认证
通过上篇文章的学习,小伙伴们对 shiro 应该有了一个大致的了解了,本文我们就来通过一个简单的案例,先来看看 shiro 中登录操作的一个基本用法。
Shiro--从一个简单的 Realm 开始权限认证