SpringBoot+SpringSecurity+jwt集成实战与初次体验
版权申诉
56 浏览量
更新于2024-09-11
1
收藏 124KB PDF 举报
"本文将详细介绍如何在SpringBoot项目中整合SpringSecurity和JWT(JSON Web Tokens)的功能,并提供初学者的实践经验和参考。作者之前使用Shiro作为安全框架,但这次选择SpringSecurity来探索其功能,同时利用JWT进行安全信息的客户端管理。
首先,确保在项目中引入了Spring Boot的security starter和JWT库。通过添加以下Maven依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
在`application.yml`配置文件中,设置JWT相关的参数,如密钥、有效期和token前缀:
```yaml
jwt:
secret: secret
expiration: 7200000
token: Authorization
```
接下来是关键的`SecurityConfig`类的配置,继承自`WebSecurityConfigurerAdapter`:
```java
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) // 开启方法级安全控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
@Autowired
private JwtUserDetailsService jwtUserDetailsService;
@Autowired
private JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// 定义权限规则
.antMatchers("/api/").authenticated()
.anyRequest().permitAll() // 其他URL允许匿名访问
.and()
// JWT验证
.csrf().disable() // 关闭CSRF保护,因为JWT提供自己的令牌验证
.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and()
.addFilterBefore(jwtAuthorizationTokenFilter, UsernamePasswordAuthenticationFilter.class);
}
@Bean
public JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint() {
return new JwtAuthenticationEntryPoint();
}
@Bean
public JwtUserDetailsService jwtUserDetailsService() {
return new JwtUserDetailsService(); // 自定义用户服务实现,用于解析JWT中的用户信息
}
@Bean
public JwtAuthorizationTokenFilter jwtAuthorizationTokenFilter() throws Exception {
return new JwtAuthorizationTokenFilter(jwtUserDetailsService, jwtProperties());
}
private JwtProperties jwtProperties() {
// 根据application.yml中的配置获取JWT相关参数
// ...
}
}
```
在这个配置中,我们设置了基本的权限策略,启用JWT验证并自定义异常处理。`JwtAuthorizationTokenFilter`负责在HTTP请求头中检查JWT,并调用`JwtUserDetailsService`解析用户信息。
文章还将涉及如何处理JWT认证错误、用户注册和登录流程,以及如何处理JWT的刷新等问题。这是一篇适合初学者理解SpringBoot、SpringSecurity和JWT集成的实用教程,有助于构建一个安全且易于扩展的Web应用架构。"
991 浏览量
313 浏览量
2024-01-16 上传
2024-03-05 上传
6184 浏览量
2024-03-03 上传
387 浏览量
2018-07-24 上传

weixin_38740397
- 粉丝: 6
最新资源
- Android PRDownloader库:支持文件下载暂停与恢复功能
- Xilinx FPGA开发实战教程(第2版)精解指南
- Aprilstore常用工具库的Java实现概述
- STM32定时开关模块DXP及完整项目资源下载指南
- 掌握IHS与PCA加权图像融合技术的Matlab实现
- JSP+MySQL+Tomcat打造简易BBS论坛及配置教程
- Volley网络通信库在Android上的实践应用
- 轻松清除或修改Windows系统登陆密码工具介绍
- Samba 4 2级免费教程:Ubuntu与Windows整合
- LeakCanary库使用演示:Android内存泄漏检测
- .Net设计要点解析与日常积累分享
- STM32 LED循环左移项目源代码与使用指南
- 中文版Windows Server服务卸载工具使用攻略
- Android应用网络状态监听与质量评估技术
- 多功能单片机电子定时器设计与实现
- Ubuntu Docker镜像整合XRDP和MATE桌面环境