spring boot学习第十三篇:使用spring security控制权限

该文章同时也讲到了如何使用swagger。

1、pom.xml文件内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.3.5.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.hmblogs</groupId><artifactId>springboot-security-demo</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot-security-demo</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!--devtools热部署--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional><scope>true</scope></dependency><!--  springboor--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.7.0</version></dependency><!-- swagger --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2、application.yml文件内容如下:

server:port: 8088servlet:context-path: /springboot-security-demospring:security:user:name: userpassword: 123456

3、SpringbootSecurityDemoApplication文件内容如下:

package com.hmblogs;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class SpringbootSecurityDemoApplication {public static void main(String[] args) {SpringApplication.run(SpringbootSecurityDemoApplication.class, args);}}

4、UserDetailsServiceImpl代码如下:

package com.hmblogs.service.impl;import java.util.ArrayList;
import java.util.List;import com.hmblogs.pojo.Admin;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.stereotype.Service;@Service
public class UserDetailsServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) {List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();Admin admin = new Admin();if (username.equals("employee")) {admin.setUsername("employee");admin.setPassword("123456");GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_EMPLOYEE");grantedAuthorities.add(grantedAuthority);// 创建用户,用户判断权限return new User(admin.getUsername(), new BCryptPasswordEncoder().encode(admin.getPassword()), grantedAuthorities);} if (username.equals("admin")) {admin.setUsername("admin");admin.setPassword("123456");GrantedAuthority grantedAuthority = new SimpleGrantedAuthority("ROLE_ADMIN");grantedAuthorities.add(grantedAuthority);// 创建用户,用户判断权限return new User(admin.getUsername(), new BCryptPasswordEncoder().encode(admin.getPassword()), grantedAuthorities);}return null;}}

5、Admin这一个对象类代码如下:

package com.hmblogs.pojo;public class Admin {private String username;private String password;public Admin() {super();}public Admin(String username, String password) {super();this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "Admin [username=" + username + ", password=" + password + "]";}}

6、TestController测试接口类代码如下所示:

package com.hmblogs.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/test/")
public class TestController {@RequestMapping(value = "get", method = RequestMethod.GET)public String get() {return "success";}}

7、EmployeeController员工权限的员工接口类代码如下所示:

package com.hmblogs.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/employee/")
public class EmployeeController {@RequestMapping(value = "greeting", method = RequestMethod.GET)public String greeting() {return "hello world";}@RequestMapping(value = "login", method = RequestMethod.GET)public String login() {return "login success";}}

8、AdminController管理员接口类的代码如下所示:

package com.hmblogs.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/admin/")
public class AdminController {@RequestMapping(value = "greeting", method = RequestMethod.GET)public String greeting() {return "hello world";}@RequestMapping(value = "login", method = RequestMethod.GET)public String login() {return "login success";}}

9、SwaggerConfig代码如下:配置swagger

package com.hmblogs.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration
@EnableSwagger2
public class SwaggerConfig {@Beanpublic Docket createRestApi(){// 添加请求参数,我们这里把token作为请求头部参数传入后端return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();}private ApiInfo apiInfo(){return new ApiInfoBuilder().title("SpringBoot API Doc").description("This is a restful api document of Spring Boot.").version("1.0").build();}}

10、SecurityConfig代码如下:

package com.hmblogs.config;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overridepublic void configure(WebSecurity web) throws Exception {super.configure(web);}@Overridepublic void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());//passwoldEncoder是对密码的加密处理,如果user中密码没有加密,则可以不加此方法。注意加密请使用security自带的加密方式。}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable()//禁用了 csrf 功能.authorizeRequests()//限定签名成功的请求.antMatchers("/decision/**","/govern/**","/employee/*").hasAnyRole("EMPLOYEE","ADMIN")//对decision和govern 下的接口 需要 EMPLOYEE 或者 ADMIN 权限.antMatchers("/employee/login").permitAll()///employee/login 不限定.antMatchers("/admin/**").hasRole("ADMIN")//对admin下的接口 需要ADMIN权限.antMatchers("/oauth/**").permitAll()//不拦截 oauth 开放的资源.anyRequest().permitAll()//其他没有限定的请求,允许访问.and().anonymous()//对于没有配置权限的其他请求允许匿名访问.and().formLogin()//使用 spring security 默认登录页面.and().httpBasic();//启用http 基础验证}}

11.CorsConfig文件代码如下:

package com.hmblogs.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class CorsConfig implements WebMvcConfigurer{@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")    // 允许跨域访问的路径.allowedOrigins("*")    // 允许跨域访问的源.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")    // 允许请求方法.maxAge(168000)    // 预检间隔时间.allowedHeaders("*")  // 允许头部设置.allowCredentials(true);    // 是否发送cookie}}

12、启动该微服务,验证。

12.1访问http://localhost:8088/springboot-security-demo/swagger-ui.html

这里我如果用户名输入admin,密码输入123456,点击登录

清除浏览器缓存后,再使用employee和123456登录,则会报401

admin账号能使用admin接口,但是employee账号不能使用admin接口。

 12.2使用admin账号密码和empoyee账号密码尝试employee接口,

先试用admin账号密码登录

清除浏览器缓存,再使用employee账号密码登录

点击登录后,查看响应,如下:

admin和employee账号都能正常访问employee接口

达到了预期目的。 

代码参考:https://github.com/veminhe/spring-security-demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/2815753.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

LeetCode238题:除自身以外数组的乘积(python3)

代码思路&#xff1a; 当前位置的结果就是它左部分的乘积再乘以它右部分的乘积&#xff0c;因此需要进行两次遍历&#xff0c;第一次遍历求左部分乘积&#xff0c;第二次遍历求右部分的乘积&#xff0c;再将最后的计算结果一起求出来。 class Solution:def productExceptSelf(…

redis中的分布式锁(setIfAbsent)(expire)

目录 应用场景 代码实例1&#xff1a; 代码实例2&#xff1a; setIfAbsent&#xff1a; expire&#xff1a; 举例说明&#xff1a; 代码实例3&#xff1a; 代码实例4&#xff1a; 还是一个同事问的一个问题&#xff0c;然后闲着没事就记录下来了。多人操作同一个保单&a…

K8S存储卷与PV,PVC

一、前言 Kubernetes&#xff08;K8s&#xff09;中的存储卷是用于在容器之间共享数据的一种机制。存储卷可以在多个Pod之间共享数据&#xff0c;并且可以保持数据的持久性&#xff0c;即使Pod被重新调度或者删除&#xff0c;数据也不会丢失。 Kubernetes支持多种类型的存储卷…

【大数据架构(2)】kappa架构介绍

文章目录 一. Kappa架构1. Speed Layer (Stream Layer) - The Foundation of Kappa Architecture2. Stream Processing: The Heart of Kappa Architecture 二. Benefits of Kappa and Streaming Architecture1. Simplicity and Streamlined Pipeline2. High-Throughput Process…

数据服务安全的重要性

数据服务安全在当今信息化社会显得尤为重要。随着大数据、云计算、人工智能等技术的飞速发展&#xff0c;数据已经成为企业和组织的核心资产&#xff0c;数据服务安全也面临着前所未有的挑战。本文将从数据服务安全的重要性、常见威胁、防护策略以及未来发展趋势等方面进行探讨…

ROS 2基础概念#1:计算图(Compute Graph)| ROS 2学习笔记

在ROS中&#xff0c;计算图&#xff08;ROS Compute Graph&#xff09;是一个核心概念&#xff0c;它描述了ROS节点之间的数据流动和通信方式。它不仅仅是一个通信网络&#xff0c;它也反映了ROS设计哲学的核心——灵活性、模块化和可重用性。通过细致探讨计算图的高级特性和实…

2024年小程序云开发CMS内容管理无法使用,无法同步内容模型到云开发数据库的解决方案,回退老版本CMS内容管理的最新方法

一&#xff0c;问题描述 最近越来越多的同学找石头哥&#xff0c;说cms用不了&#xff0c;其实是小程序官方最近又搞大动作了&#xff0c;偷偷的升级的云开发cms&#xff08;内容管理&#xff09;以下都称cms&#xff0c;不升级不要紧&#xff0c;这一升级&#xff0c;就导致我…

鸿蒙(HarmonyOS)项目方舟框架(ArkUI)之FlowItem容器组件

鸿蒙&#xff08;HarmonyOS&#xff09;项目方舟框架&#xff08;ArkUI&#xff09;之FlowItem容器组件 一、操作环境 操作系统: Windows 10 专业版、IDE:DevEco Studio 3.1、SDK:HarmonyOS 3.1 二、FlowItem组件 子组件 可以包含子组件。 接口 FlowItem() 使用该接口来…

Android14之解决编译报错:bazel: no such file or directory(一百八十九)

简介&#xff1a; CSDN博客专家&#xff0c;专注Android/Linux系统&#xff0c;分享多mic语音方案、音视频、编解码等技术&#xff0c;与大家一起成长&#xff01; 优质专栏&#xff1a;Audio工程师进阶系列【原创干货持续更新中……】&#x1f680; 优质专栏&#xff1a;多媒…

Stable Diffusion WebUI 图库浏览器插件:浏览器以前生成的图片

本文收录于《AI绘画从入门到精通》专栏&#xff0c;专栏总目录&#xff1a;点这里。 大家好&#xff0c;我是水滴~~ 本文介绍的插件叫图库浏览器&#xff0c;是一个用于浏览器以前生成的图片信息的插件。本文将介绍该插件的安装和使用&#xff0c;希望能够对你有所帮助。 文章…

GitHub宣布GitHub Copilot Enterprise的全面发布;使用Python与Gemma和MongoDB构建RAG系统的全过程

&#x1f989; AI新闻 &#x1f680; GitHub宣布GitHub Copilot Enterprise的全面发布 摘要&#xff1a;GitHub Copilot Enterprise是一款基于OpenAI的GPT-4模型的代码助手&#xff0c;它结合了十多年的真实、安全可靠的代码数据进行开发。该工具可以通过文本提示来获取、审核…

JavaEE进阶(7)Spring Boot 日志(概述、用途、使用:打印日志,框架介绍,SLF4J 框架介绍、更简单的日志输出)

接上次博客&#xff1a;JavaEE进阶&#xff08;6&#xff09;SpringBoot 配置文件&#xff08;作用、格式、properties配置文件说明、yml配置文件说明、验证码案例&#xff09;-CSDN博客 目录 日志概述 日志的用途 日志使用 打印日志 在程序中获取日志对象 使用日志对象…

练习 3 Web [ACTF2020 新生赛]Upload

[ACTF2020 新生赛]Upload1 中间有上传文件的地方&#xff0c;试一下一句话木马 txt 不让传txt 另存为tlyjpg&#xff0c;木马文件上传成功 给出了存放目录&#xff1a; Upload Success! Look here~ ./uplo4d/06a9d80f64fded1e542a95e6d530c70a.jpg 下一步尝试改木马文件后缀…

Python的自然语言处理库NLTK介绍

NLTK&#xff08;Natural Language Toolkit&#xff09;简介 NLTK是Python中一个领先的自然语言处理&#xff08;NLP&#xff09;库&#xff0c;它提供了文本处理的基础设施&#xff0c;包括分词&#xff08;tokenization&#xff09;、词性标注&#xff08;part-of-speech tag…

云计算与边缘计算:有何不同?

公共云计算平台可以帮助企业充分利用全球服务器来增强其私有数据中心。这使得基础设施能够扩展到任何位置&#xff0c;并有助于计算资源的灵活扩展。混合公共-私有云为企业计算应用程序提供了强大的灵活性、价值和安全性。 然而&#xff0c;随着分布在全球各地的实时人工智能应…

亚马逊自养号测评:如何安全搭建环境,有效规避风险

要在亚马逊上进行自养号测评&#xff0c;构建一个真实的国外环境至关重要。这包括模拟国外的服务器、IP地址、浏览器环境&#xff0c;甚至支付方式&#xff0c;以创建一个完整的国际操作环境。这样的环境能让我们自由注册、养号并下单&#xff0c;确保所有操作均符合国际规范。…

十三、Qt多线程与线程安全

一、多线程程序 QThread类提供了管理线程的方法&#xff1a;一个对象管理一个线程一般从QThread继承一个自定义类&#xff0c;重载run函数 1、实现程序 &#xff08;1&#xff09;创建项目&#xff0c;基于QDialog &#xff08;2&#xff09;添加类&#xff0c;修改基于QThr…

微软广告和网络服务CEO承认OpenAI的Sora将加入Copilot,但需要一些时间

事情的起因是一名网友询问 Sora 是否会加入 Copilot&#xff0c;微软广告和网络服务CEO首席执行官——Mikhail Parakhin 回应说&#xff1a;“最终&#xff0c;但这需要时间。”毕竟投了几十个亿美金进去&#xff0c;不亏是金主爸爸。 图为Mikhail Parakhin Sora是OpenAI开发的…

2024年阿里云2核4G配置服务器测评_ECS和轻量性能测评

阿里云2核4G服务器多少钱一年&#xff1f;2核4G服务器1个月费用多少&#xff1f;2核4G服务器30元3个月、85元一年&#xff0c;轻量应用服务器2核4G4M带宽165元一年&#xff0c;企业用户2核4G5M带宽199元一年。本文阿里云服务器网整理的2核4G参加活动的主机是ECS经济型e实例和u1…

nginx 日志,压缩,https功能介绍

一&#xff0c; 自定义访问日志 &#xff08;一&#xff09;日志位置存放 1&#xff0c;格式 2&#xff0c; 级别 level: debug, info, notice, warn, error, crit, alert, emerg 3&#xff0c;示例 服务机定义 错误日志存放位置 客户机错误访问 查看错误日志 4&#xff…