SpringBoot+SpringSecurity+jwt集成实战与初次体验
版权申诉
82 浏览量
更新于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应用架构。"
995 浏览量
495 浏览量
467 浏览量
2024-01-16 上传
2024-03-05 上传
6154 浏览量
2024-03-03 上传
387 浏览量
2018-07-24 上传
![](https://profile-avatar.csdnimg.cn/default.jpg!1)
weixin_38740397
- 粉丝: 6
最新资源
- MATLAB 2006神经网络工具箱用户指南
- INFORMIX监控与管理命令详解:SMI与TBSTAT操作
- Intel Threading Building Blocks:引领C++并行编程新时代
- C++泛型编程深入指南:模板完全解析
- 精通组件编程:COM/DCOM实例解析与Office二次开发
- UNIX基础入门:常用命令详解与操作
- Servlet基础入门:生命周期与配置详解
- HTTP状态码详解:成功、重定向与信息响应
- Java Web Services:构建与集成指南
- LDAP技术详解:从X.500到ActiveDirectory
- MyEclipse开发JSF实战教程:快速入门
- 刘长炯MyEclipse 6.0入门教程:快速安装与开发指南
- Linux环境下安装配置Tomcat指南
- Eclipse与Lomboz插件助力J2EE开发:从WebSphere到WebLogic
- Oracle数据库操作:自定义函数与记录处理
- 谭浩强C语言基础:数据类型、运算符与表达式解析