当前位置: 首页 > news >正文

Spring Boot中的安全配置与实现

Spring Boot中的安全配置与实现

大家好,我是免费搭建查券返利机器人省钱赚佣金就用微赚淘客系统3.0的小编,也是冬天不穿秋裤,天冷也要风度的程序猿!今天我们将深入探讨Spring Boot中的安全配置与实现,看看如何保护你的应用免受潜在的安全威胁。

一、Spring Boot中的安全框架简介

Spring Boot集成了Spring Security,这是一个强大的认证和授权框架,用于保护基于Spring的应用程序。Spring Security提供了许多功能,如基于角色的访问控制、表单登录、HTTP Basic认证、OAuth 2.0支持等。

1. Maven依赖

首先,确保在pom.xml文件中添加Spring Security的依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>

二、基本的安全配置

1. 创建安全配置类

创建一个继承自WebSecurityConfigurerAdapter的配置类,用于定义安全策略。

package cn.juwatech.springboot.config;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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

2. 配置登录页面

创建一个简单的登录页面login.html,放置在src/main/resources/templates目录下:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head><title>Login</title>
</head>
<body><div><h2>Login</h2><form th:action="@{/login}" method="post"><div><label>Username: <input type="text" name="username"></label></div><div><label>Password: <input type="password" name="password"></label></div><div><input type="submit" value="Sign in"></div></form></div>
</body>
</html>

三、基于注解的安全控制

Spring Security支持基于注解的安全控制,使用@PreAuthorize@Secured注解可以在方法级别进行权限控制。

1. 使用@Secured注解

在服务类的方法上使用@Secured注解,指定角色权限。

package cn.juwatech.springboot.service;import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;@Service
public class UserService {@Secured("ROLE_ADMIN")public String adminMethod() {return "Admin access only";}@Secured("ROLE_USER")public String userMethod() {return "User access only";}
}

2. 使用@PreAuthorize注解

使用@PreAuthorize注解支持SpEL(Spring Expression Language)表达式,实现更复杂的权限控制。

package cn.juwatech.springboot.service;import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;@Service
public class SecureService {@PreAuthorize("hasRole('ADMIN')")public String adminOnly() {return "Admin access only";}@PreAuthorize("hasRole('USER') and #id == principal.id")public String userOnly(Long id) {return "User access for ID: " + id;}
}

四、使用JWT进行安全认证

JWT(JSON Web Token)是一种轻量级的认证机制,常用于移动和Web应用的认证。

1. 添加JWT依赖

pom.xml中添加JWT相关依赖:

<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version>
</dependency>

2. 创建JWT工具类

实现一个JWT工具类,负责生成和解析JWT。

package cn.juwatech.springboot.security;import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;import java.util.Date;@Component
public class JwtUtil {private String secretKey = "secret";public String generateToken(String username) {return Jwts.builder().setSubject(username).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 10)).signWith(SignatureAlgorithm.HS256, secretKey).compact();}public Claims extractClaims(String token) {return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token).getBody();}public String extractUsername(String token) {return extractClaims(token).getSubject();}public boolean isTokenExpired(String token) {return extractClaims(token).getExpiration().before(new Date());}public boolean validateToken(String token, String username) {return (username.equals(extractUsername(token)) && !isTokenExpired(token));}
}

3. 集成JWT认证

在Spring Security配置中集成JWT认证。

package cn.juwatech.springboot.config;import cn.juwatech.springboot.security.JwtUtil;
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.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate JwtUtil jwtUtil;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().withUser("user").password(passwordEncoder().encode("password")).roles("USER").and().withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN");}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasRole("USER").anyRequest().authenticated().and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);http.addFilterBefore(new JwtRequestFilter(jwtUtil), UsernamePasswordAuthenticationFilter.class);}@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}
}

四、总结

通过本文,我们全面了解了在Spring Boot中实现安全配置的各种方法,包括基本的安全配置、基于注解的权限控制以及如何集成JWT进行认证。Spring Security提供了丰富的功能,使得应用程序的安全性得到有效保障。

微赚淘客系统3.0小编出品,必属精品!

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 如何指定多块GPU卡进行训练-数据并行
  • UOS统信系统开机启动故障
  • Linux系统密码重置
  • [综述笔记]Functional neuroimaging as a catalyst for integrated neuroscience
  • ES13的4个改革性新特性
  • vue3中antd上传图片组件及回显
  • Android OkHttp3中HttpLoggingInterceptor使用
  • CV10_模型、特征图、CAM热力图可视化
  • 玩转springboot之SpringApplicationRunListener
  • 能够支持百度独立导航的智能手表你见过吗?
  • 【学习笔记】无人机(UAV)在3GPP系统中的增强支持(一)-3GPP TR 22.829 V17.1.0技术报告
  • Rust编程-I/O
  • 算法刷题笔记 合并集合(C++实现)
  • TensorBoard ,PIL 和 OpenCV 在深度学习中的应用
  • python--实验 11 模块
  • 【Amaple教程】5. 插件
  • 【刷算法】求1+2+3+...+n
  • 2019年如何成为全栈工程师?
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • java B2B2C 源码多租户电子商城系统-Kafka基本使用介绍
  • JSONP原理
  • Mocha测试初探
  • Python实现BT种子转化为磁力链接【实战】
  • 百度贴吧爬虫node+vue baidu_tieba_crawler
  • 浮动相关
  • 利用阿里云 OSS 搭建私有 Docker 仓库
  • 前言-如何学习区块链
  • 浅谈JavaScript的面向对象和它的封装、继承、多态
  • 如何用Ubuntu和Xen来设置Kubernetes?
  • 如何在GitHub上创建个人博客
  • 如何抓住下一波零售风口?看RPA玩转零售自动化
  • 再次简单明了总结flex布局,一看就懂...
  • 湖北分布式智能数据采集方法有哪些?
  • ​什么是bug?bug的源头在哪里?
  • !!Dom4j 学习笔记
  • $redis-setphp_redis Set命令,php操作Redis Set函数介绍
  • (14)目标检测_SSD训练代码基于pytorch搭建代码
  • (20050108)又读《平凡的世界》
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (八十八)VFL语言初步 - 实现布局
  • (附源码)ssm基于jsp的在线点餐系统 毕业设计 111016
  • (附源码)小程序 交通违法举报系统 毕业设计 242045
  • (机器学习的矩阵)(向量、矩阵与多元线性回归)
  • (十)c52学习之旅-定时器实验
  • (算法)硬币问题
  • (转)从零实现3D图像引擎:(8)参数化直线与3D平面函数库
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .NET 中小心嵌套等待的 Task,它可能会耗尽你线程池的现有资源,出现类似死锁的情况
  • .Net下使用 Geb.Video.FFMPEG 操作视频文件
  • @德人合科技——天锐绿盾 | 图纸加密软件有哪些功能呢?
  • [ CTF ]【天格】战队WriteUp- 2022年第三届“网鼎杯”网络安全大赛(青龙组)
  • [ 代码审计篇 ] 代码审计案例详解(一) SQL注入代码审计案例
  • [2016.7.Test1] T1 三进制异或
  • [28期] lamp兄弟连28期学员手册,请大家务必看一下
  • [android] 练习PopupWindow实现对话框