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://www.hqwc.cn/news/498167.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【深度学习】SDXL-Lightning 体验,gradio教程,SDXL-Lightning 论文

文章目录 资源SDXL-Lightning 论文 资源 SDXL-Lightning论文&#xff1a;https://arxiv.org/abs/2402.13929 gradio教程&#xff1a;https://blog.csdn.net/qq_21201267/article/details/131989242 SDXL-Lightning &#xff1a;https://huggingface.co/ByteDance/SDXL-Light…

蓝桥杯_定时器的基本原理与应用

一 什么是定时器 定时器/计数器是一种能够对内部时钟信号或外部输入信号进行计数&#xff0c;当计数值达到设定要求时&#xff0c;向cpu提出中断处理请求&#xff0c;从而实现&#xff0c;定时或者计数功能的外设。 二 51单片机的定时/计数器 单片机外部晶振12MHZ&#xff0c;…

Facebook的元宇宙实践:数字化社交的新前景

近年来&#xff0c;元宇宙&#xff08;Metaverse&#xff09;这一概念备受瞩目&#xff0c;被认为是数字化社交的未来趋势之一。而在众多科技巨头中&#xff0c;Facebook&#xff08;现更名为Meta&#xff09;一直处于元宇宙发展的前沿。在本文中&#xff0c;我们将深入探讨Fac…

火灾安全护航:火灾监测报警摄像机助力建筑安全

火灾是建筑安全中最常见也最具破坏力的灾难之一&#xff0c;为了及时发现火灾、减少火灾造成的损失&#xff0c;火灾监测报警摄像机应运而生&#xff0c;成为建筑防火安全的重要技术装备。 火灾监测报警摄像机采用高清晰度摄像头和智能识别系统&#xff0c;能够全天候监测建筑内…

下载huggingface数据集到本地并读取.arrow文件遇到的问题

文章目录 1. 524MB中文维基百科语料&#xff08;需要下载的数据集&#xff09;2. 下载 hugging face 网站上的数据集3. 读取 .arrow 文件报错代码4. 纠正后代码 1. 524MB中文维基百科语料&#xff08;需要下载的数据集&#xff09; 2. 下载 hugging face 网站上的数据集 要将H…

视频二维码生成的应用领域:探寻多彩世界的大门

在数字化时代&#xff0c;生成二维码已成为连接线上线下的桥梁&#xff0c;而视频二维码则为信息传递注入了全新的生机和活力。二维码不再只是静态的黑白方块&#xff0c;通过二维彩虹技术的运用&#xff0c;视频二维码打开了一扇通往多彩世界的大门&#xff0c;让我们一同探寻…

【Java程序员面试专栏 算法思维】一 高频面试算法题:排序算法

一轮的算法训练完成后,对相关的题目有了一个初步理解了,接下来进行专题训练,以下这些题目就是汇总的高频题目,本篇主要聊聊排序算法,包括手撕排序算法,经典的TOPK问题以及区间合并,所以放到一篇Blog中集中练习 题目关键字解题思路时间空间快速排序双指针+递归+基准值分…

半导体行业案例:Jira与龙智插件助力某半导体企业实现精益项目管理

近日&#xff0c;龙智Atlassian技术团队收到了国内一家大型半导体企业的感谢信。龙智团队提供的半导体行业项目管理解决方案和服务受到了客户的好评&#xff1a; 在龙智团队的支持下&#xff0c;我们的业务取得了喜人的成果和进步。龙智公司的专业服务和产品&#xff0c;是我们…

预约出行真方便!苏州金龙海格客车服务京津冀上班族总运量破百万

元宵已过&#xff0c;全国各地上班族们纷纷回到各自的岗位&#xff0c;通勤路也再次变得繁忙。近日&#xff0c;“京津冀协同合作打造环京通勤定制快巴网络”入选交通运输部公布的道路客运转型发展典型案例。截至2023年11月底&#xff0c;京津冀定制快巴已开通北京至河北燕郊、…

c# ABB 机械手上位机连接

c# 程式开发和调试步骤如下&#xff1a; ABB 机械手要开启PC Interface功能。ABB 机械手设定ip地址。设定测试笔记本和机械手同一网段&#xff0c;用网线直连机械手&#xff0c;也可以通过交换机连接机械手。确保笔记本能够ping通和telnet 机械手80端口都是OK的。以上都OK的话…

阿里云A10推理qwen

硬件配置 vCPU&#xff1a;32核 内存&#xff1a;188 GiB 宽带&#xff1a;5 Mbps GPU&#xff1a;NVIDIA A10 24Gcuda 安装 wget https://developer.download.nvidia.com/compute/cuda/12.1.0/local_installers/cuda-repo-rhel7-12-1-local-12.1.0_530.30.02-1.x86_64.rpm s…

js 手写深拷贝方法

文章目录 一、深拷贝实现代码二、代码讲解2.1 obj.constructor(obj)2.2 防止循环引用 手写一个深拷贝是我们常见的面试题&#xff0c;在实现过程中我们需要考虑的类型很多&#xff0c;包括对象、数组、函数、日期等。以下就是深拷贝实现逻辑 一、深拷贝实现代码 const origin…