springboot配置jwt

时间: 2023-09-30 09:06:26 浏览: 136
在Spring Boot应用程序中,配置JWT的步骤如下: 1. 添加相关的依赖:在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> ``` 2. 创建一个JWT工具类:该类用于处理JWT的生成和验证。以下是一个简单的示例: ``` import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.stereotype.Component; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.function.Function; @Component public class JwtTokenUtil { private static final long JWT_TOKEN_VALIDITY = 5 * 60 * 60; @Value("${jwt.secret}") private String secret; public String getUsernameFromToken(String token) { return getClaimFromToken(token, Claims::getSubject); } public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token, Claims::getExpiration); } public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) { final Claims claims = getAllClaimsFromToken(token); return claimsResolver.apply(claims); } private Claims getAllClaimsFromToken(String token) { return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody(); } private Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, userDetails.getUsername()); } private String doGenerateToken(Map<String, Object> claims, String subject) { final Date createdDate = new Date(); final Date expirationDate = new Date(createdDate.getTime() + JWT_TOKEN_VALIDITY * 1000); return Jwts.builder().setClaims(claims).setSubject(subject) .setIssuedAt(createdDate).setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, secret).compact(); } public Boolean validateToken(String token, UserDetails userDetails) { final String username = getUsernameFromToken(token); return (username.equals(userDetails.getUsername()) && !isTokenExpired(token)); } } ``` 3. 创建一个JWT过滤器:该过滤器用于验证请求的JWT。以下是一个简单的示例: ``` import io.jsonwebtoken.ExpiredJwtException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Component; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class JwtRequestFilter extends OncePerRequestFilter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtTokenUtil jwtTokenUtil; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { final String requestTokenHeader = request.getHeader("Authorization"); String username = null; String jwtToken = null; if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) { jwtToken = requestTokenHeader.substring(7); try { username = jwtTokenUtil.getUsernameFromToken(jwtToken); } catch (IllegalArgumentException e) { logger.error("Unable to get JWT Token"); } catch (ExpiredJwtException e) { logger.error("JWT Token has expired"); } } else { logger.warn("JWT Token does not begin with Bearer String"); } if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(username); if (jwtTokenUtil.validateToken(jwtToken, userDetails)) { UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken( userDetails, null, userDetails.getAuthorities()); usernamePasswordAuthenticationToken .setDetails(new WebAuthenticationDetailsSource().buildDetails(request)); SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken); } } chain.doFilter(request, response); } } ``` 4. 在Spring Boot应用程序中配置JWT:您需要在应用程序配置文件中添加以下属性: ``` jwt.secret=your_secret_key_here ``` 5. 在Spring Boot应用程序中启用JWT:您需要在Spring Boot应用程序中启用JWT。以下是一个简单的示例: ``` import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.security.authentication.AuthenticationManager; 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.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @SpringBootApplication(exclude = {SecurityAutoConfiguration.class}) @EnableWebSecurity public class Application extends WebSecurityConfigurerAdapter { @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Autowired private UserDetailsService jwtUserDetailsService; @Autowired private JwtRequestFilter jwtRequestFilter; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(jwtUserDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public JwtAuthenticationEntryPoint jwtAuthenticationEntryPointBean() throws Exception { return new JwtAuthenticationEntryPoint(); } @Bean public JwtRequestFilter jwtRequestFilterBean() throws Exception { return new JwtRequestFilter(); } @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(HttpSecurity httpSecurity) throws Exception { httpSecurity.csrf().disable() .authorizeRequests().antMatchers("/authenticate").permitAll(). anyRequest().authenticated().and(). exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS); httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 以上就是在Spring Boot应用程序中配置JWT的基本步骤。
阅读全文

相关推荐

最新推荐

recommend-type

Springboot+SpringSecurity+JWT实现用户登录和权限认证示例

7. **Spring Security配置**:配置Spring Security以启用JWT认证,设置访问控制规则,例如哪些URL需要认证,哪些URL对所有用户开放。 8. **认证Controller**:创建一个专门处理用户登录请求的Controller,接收登录...
recommend-type

自动删除hal库spendsv、svc以及systick中断

自动删除hal库spendsv、svc以及systick中断
recommend-type

流量主小程序 多功能工具箱小程序源码-操作简单实用.zip

这是一款多功能工具箱小程序! 目前由N款小功能组合成 比如: 图片拼接 九宫格切图 透明昵称 文字表情 等等上面说的只是一部分
recommend-type

基于Simulink的PEMFC燃料电池机理模型(密歇根大学开发,涵盖空压机、空气路、氢气路及电堆仿真),基于Simulink的PEMFC燃料电池机理模型(密歇根大学开发,涵盖空压机、空气路、氢气路及

基于Simulink的PEMFC燃料电池机理模型(密歇根大学开发,涵盖空压机、空气路、氢气路及电堆仿真),基于Simulink的PEMFC燃料电池机理模型(密歇根大学开发,涵盖空压机、空气路、氢气路及电堆仿真),基于simulink建立的PEMFC燃料电池机理模型(国外团队开发的,密歇根大学),包含空压机模型,空气路,氢气路,电堆等模型。 可以正常进行仿真。 ,PEMFC燃料电池模型; 空压机模型; 空气路模型; 氢气路模型; 电堆模型; 仿真。,密歇根大学PEMFC燃料电池机理模型:Simulink仿真空氢电堆一体化模型
recommend-type

世界地图Shapefile文件解析与测试指南

标题中提到的“世界地图的shapefile文件”,涉及到两个关键概念:世界地图和shapefile文件格式。首先我们来解释这两个概念。 世界地图是一个地理信息系统(GIS)中常见的数据类型,通常包含了世界上所有或大部分国家、地区、自然地理要素的图形表达。世界地图可以以多种格式存在,比如栅格数据格式(如JPEG、PNG图片)和矢量数据格式(如shapefile、GeoJSON、KML等)。 shapefile文件是一种流行的矢量数据格式,由ESRI(美国环境系统研究所)开发。它主要用于地理信息系统(GIS)软件,用于存储地理空间数据及其属性信息。shapefile文件实际上是一个由多个文件组成的文件集,这些文件包括.shp、.shx、.dbf等文件扩展名,分别存储了图形数据、索引、属性数据等。这种格式广泛应用于地图制作、数据管理、空间分析以及地理研究。 描述提到,这个shapefile文件适合应用于解析shapefile程序的测试。这意味着该文件可以被用于测试或学习如何在程序中解析shapefile格式的数据。对于GIS开发人员或学习者来说,能够处理和解析shapefile文件是一项基本而重要的技能。它需要对文件格式有深入了解,以及如何在各种编程语言中读取和写入这些文件。 标签“世界地图 shapefile”为这个文件提供了两个关键词。世界地图指明了这个shapefile文件内容的地理范围,而shapefile指明了文件的数据格式。标签的作用通常是用于搜索引擎优化,帮助人们快速找到相关的内容或文件。 在压缩包子文件的文件名称列表中,我们看到“wold map”这个名称。这应该是“world map”的误拼。这提醒我们在处理文件时,确保文件名称的准确性和规范性,以避免造成混淆或搜索不便。 综合以上信息,知识点的详细介绍如下: 1. 世界地图的概念:世界地图是地理信息系统中一个用于表现全球或大范围区域地理信息的图形表现形式。它可以显示国界、城市、地形、水体等要素,并且可以包含多种比例尺。 2. shapefile文件格式:shapefile是一种矢量数据格式,非常适合用于存储和传输地理空间数据。它包含了多个相关联的文件,以.shp、.shx、.dbf等文件扩展名存储不同的数据内容。每种文件类型都扮演着关键角色: - .shp文件:存储图形数据,如点、线、多边形等地理要素的几何形状。 - .shx文件:存储图形数据的索引,便于程序快速定位数据。 - .dbf文件:存储属性数据,即与地理要素相关联的非图形数据,例如国名、人口等信息。 3. shapefile文件的应用:shapefile文件在GIS应用中非常普遍,可以用于地图制作、数据编辑、空间分析、地理数据的共享和交流等。由于其广泛的兼容性,shapefile格式被许多GIS软件所支持。 4. shapefile文件的处理:GIS开发人员通常需要在应用程序中处理shapefile数据。这包括读取shapefile数据、解析其内容,并将其用于地图渲染、空间查询、数据分析等。处理shapefile文件时,需要考虑文件格式的结构和编码方式,正确解析.shp、.shx和.dbf文件。 5. shapefile文件的测试:shapefile文件在开发GIS相关程序时,常被用作测试材料。开发者可以使用已知的shapefile文件,来验证程序对地理空间数据的解析和处理是否准确无误。测试过程可能包括读取测试、写入测试、空间分析测试等。 6. 文件命名的准确性:文件名称应该准确无误,以避免在文件存储、传输或检索过程中出现混淆。对于地理数据文件来说,正确的命名还对确保数据的准确性和可检索性至关重要。 以上知识点涵盖了世界地图shapefile文件的基础概念、技术细节、应用方式及处理和测试等重要方面,为理解和应用shapefile文件提供了全面的指导。
recommend-type

Python环境监控高可用构建:可靠性增强的策略

# 1. Python环境监控高可用构建概述 在构建Python环境监控系统时,确保系统的高可用性是至关重要的。监控系统不仅要在系统正常运行时提供实时的性能指标,而且在出现故障或性能瓶颈时,能够迅速响应并采取措施,避免业务中断。高可用监控系统的设计需要综合考虑监控范围、系统架构、工具选型等多个方面,以达到对资源消耗最小化、数据准确性和响应速度最优化的目
recommend-type

需要在matlab当中批量导入表格数据的指令

### 如何在 MATLAB 中批量导入表格数据 为了高效地处理多个表格文件,在 MATLAB 中可以利用脚本自动化这一过程。通过编写循环结构读取指定目录下的所有目标文件并将其内容存储在一个统一的数据结构中,能够显著提升效率。 对于 Excel 文件而言,`readtable` 函数支持直接从 .xls 或者 .xlsx 文件创建 table 类型变量[^2]。当面对大量相似格式的 Excel 表格时,可以通过遍历文件夹内的每一个文件来完成批量化操作: ```matlab % 定义要扫描的工作路径以及输出保存位置 inputPath = 'C:\path\to\your\excelFil
recommend-type

Sqlcipher 3.4.0版本发布,优化SQLite兼容性

从给定的文件信息中,我们可以提取到以下知识点: 【标题】: "sqlcipher-3.4.0" 知识点: 1. SQLCipher是一个开源的数据库加密扩展,它为SQLite数据库增加了透明的256位AES加密功能,使用SQLCipher加密的数据库可以在不需要改变原有SQL语句和应用程序逻辑的前提下,为存储在磁盘上的数据提供加密保护。 2. SQLCipher版本3.4.0表示这是一个特定的版本号。软件版本号通常由主版本号、次版本号和修订号组成,可能还包括额外的前缀或后缀来标识特定版本的状态(如alpha、beta或RC - Release Candidate)。在这个案例中,3.4.0仅仅是一个版本号,没有额外的信息标识版本状态。 3. 版本号通常随着软件的更新迭代而递增,不同的版本之间可能包含新的特性、改进、修复或性能提升,也可能是对已知漏洞的修复。了解具体的版本号有助于用户获取相应版本的特定功能或修复。 【描述】: "sqlcipher.h是sqlite3.h的修正,避免与系统预安装sqlite冲突" 知识点: 1. sqlcipher.h是SQLCipher项目中定义特定加密功能和配置的头文件。它基于SQLite的头文件sqlite3.h进行了定制,以便在SQLCipher中提供数据库加密功能。 2. 通过“修正”原生SQLite的头文件,SQLCipher允许用户在相同的编程环境或系统中同时使用SQLite和SQLCipher,而不会引起冲突。这是因为两者共享大量的代码基础,但SQLCipher扩展了SQLite的功能,加入了加密支持。 3. 系统预安装的SQLite可能与需要特定SQLCipher加密功能的应用程序存在库文件或API接口上的冲突。通过使用修正后的sqlcipher.h文件,开发者可以在不改动现有SQLite数据库架构的基础上,将应用程序升级或迁移到使用SQLCipher。 4. 在使用SQLCipher时,开发者需要明确区分它们的头文件和库文件,避免链接到错误的库版本,这可能会导致运行时错误或安全问题。 【标签】: "sqlcipher" 知识点: 1. 标签“sqlcipher”直接指明了这个文件与SQLCipher项目有关,说明了文件内容属于SQLCipher的范畴。 2. 一个标签可以用于过滤、分类或搜索相关的文件、代码库或资源。在这个上下文中,标签可能用于帮助快速定位或检索与SQLCipher相关的文件或库。 【压缩包子文件的文件名称列表】: sqlcipher-3.4.0 知识点: 1. 由于给出的文件名称列表只有一个条目 "sqlcipher-3.4.0",它很可能指的是压缩包文件名。这表明用户可能下载了一个压缩文件,解压后的内容应该与SQLCipher 3.4.0版本相关。 2. 压缩文件通常用于减少文件大小或方便文件传输,尤其是在网络带宽有限或需要打包多个文件时。SQLCipher的压缩包可能包含头文件、库文件、示例代码、文档、构建脚本等。 3. 当用户需要安装或更新SQLCipher到特定版本时,他们通常会下载对应的压缩包文件,并解压到指定目录,然后根据提供的安装指南或文档进行编译和安装。 4. 文件名中的版本号有助于确认下载的SQLCipher版本,确保下载的压缩包包含了期望的特性和功能。 通过上述详细解析,我们可以了解到关于SQLCipher项目版本3.4.0的相关知识,以及如何处理和使用与之相关的文件。
recommend-type

Python环境监控性能监控与调优:专家级技巧全集

# 1. Python环境性能监控概述 在当今这个数据驱动的时代,随着应用程序变得越来越复杂和高性能化,对系统性能的监控和优化变得至关重要。Python作为一种广泛应用的编程语言,其环境性能监控不仅能够帮助我们了解程序运行状态,还能及时发现潜在的性能瓶颈,预防系统故障。本章将概述Python环境性能监控的重要性,提供一个整体框架,以及为后续章节中深入探讨各个监控技术打
recommend-type

simulinlk怎么插入线

### 如何在 Simulink 中添加或插入连接线 在 Simulink 中创建模型时,连接线用于表示信号从一个模块传递到另一个模块。以下是几种常见的方法来添加或插入连接线: #### 使用鼠标拖拽法 通过简单的鼠标操作可以快速建立两个模块之间的连接。当光标悬停在一个模块的输入端口或输出端口上时,会出现一个小圆圈提示可连接区域;此时按住左键并拖动至目标位置即可完成连线[^1]。 #### 利用手绘模式绘制直线段 对于更复杂的路径需求,则可以通过手绘方式精确控制每一段线路走向。例如,在 MATLAB 命令窗口中执行如下代码片段能够实现特定坐标的短折线绘制: ```matlab annot