springboot security项目 如何封装jwt 及token 其中数据表为package com.aokace.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter; /** * <p> * * </p> * * @author aokace * @since 2023-05-23 */ @Getter @Setter @TableName("user") @ApiModel(value = "User对象", description = "") public class User implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "userid", type = IdType.AUTO) private Integer userid; @TableField("authority") private String authority; @TableField("role") private String role; @TableField("username") private String username; @TableField("password") private String password; }

时间: 2024-01-05 13:03:02 浏览: 87
首先需要引入相关的依赖,包括JWT和Spring Security的依赖: ``` <dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 然后创建一个JwtTokenUtil类来实现JWT的签发和验证功能: ```java import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; 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; @Component public class JwtTokenUtil { private static final String CLAIM_KEY_USERNAME = "sub"; private static final String CLAIM_KEY_CREATED = "created"; @Value("${jwt.secret}") private String secret; @Value("${jwt.expiration}") private Long expiration; public String generateToken(UserDetails userDetails) { Map<String, Object> claims = new HashMap<>(); claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername()); claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } public String getUsernameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; } public Date getCreatedDateFromToken(String token) { Date created; try { Claims claims = getClaimsFromToken(token); created = new Date((Long) claims.get(CLAIM_KEY_CREATED)); } catch (Exception e) { created = null; } return created; } public Date getExpirationDateFromToken(String token) { Date expiration; try { Claims claims = getClaimsFromToken(token); expiration = claims.getExpiration(); } catch (Exception e) { expiration = null; } return expiration; } public boolean isTokenExpired(String token) { Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } public String refreshToken(String token) { String refreshedToken; try { Claims claims = getClaimsFromToken(token); claims.put(CLAIM_KEY_CREATED, new Date()); refreshedToken = generateToken(claims); } catch (Exception e) { refreshedToken = null; } return refreshedToken; } public boolean validateToken(String token, UserDetails userDetails) { String username = getUsernameFromToken(token); return username.equals(userDetails.getUsername()) && !isTokenExpired(token); } private Claims getClaimsFromToken(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(secret) .parseClaimsJws(token) .getBody(); } catch (Exception e) { claims = null; } return claims; } private String generateToken(Map<String, Object> claims) { Date expirationDate = new Date(System.currentTimeMillis() + expiration * 1000); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, secret); return builder.compact(); } } ``` 其中,JwtTokenUtil类中的generateToken方法用于生成JWT Token,getUsernameFromToken和getExpirationDateFromToken方法用于解析JWT Token中的用户名和过期时间,isTokenExpired方法用于判断JWT Token是否已经过期,refreshToken方法用于刷新JWT Token,validateToken方法用于验证JWT Token是否有效,getClaimsFromToken方法用于从JWT Token中获取Claims。 然后在Spring Security的配置类中添加JwtTokenFilter来实现JWT的过滤和验证: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Autowired private JwtTokenFilter jwtTokenFilter; @Autowired private JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint) .and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class); } @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ``` 其中,SecurityConfig类中的configure方法用于配置Spring Security的策略,addFilterBefore方法用于添加JwtTokenFilter,authenticationManagerBean方法用于获取AuthenticationManager。 最后,在登录接口中,使用JwtTokenUtil生成JWT Token并返回给前端: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController public class AuthController { @Autowired private AuthenticationManager authenticationManager; @Autowired private JwtTokenUtil jwtTokenUtil; @Autowired private UserDetailsService userDetailsService; @PostMapping("/login") public ResponseEntity<?> login(@RequestBody AuthRequest authRequest) throws Exception { try { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(authRequest.getUsername(), authRequest.getPassword()) ); UserDetails userDetails = userDetailsService.loadUserByUsername(authRequest.getUsername()); String token = jwtTokenUtil.generateToken(userDetails); return ResponseEntity.ok(new AuthResponse(token)); } catch (Exception e) { throw new Exception("Incorrect username or password", e); } } } ``` 其中,AuthController类中的login方法用于处理登录请求,通过authenticationManager.authenticate方法验证用户名和密码,然后使用JwtTokenUtil生成JWT Token并返回给前端。

相关推荐

最新推荐

recommend-type

基于springboot+jwt实现刷新token过程解析

基于SpringBoot+JWT实现刷新Token过程解析 标题解析 本文主要介绍了基于SpringBoot和JWT实现刷新Token的过程解析,旨在帮助读者更好地理解Token的刷新机制和实现方式。 描述解析 文中通过示例代码详细介绍了基于...
recommend-type

SpringSecurity Jwt Token 自动刷新的实现

SpringSecurity Jwt Token 自动刷新的实现 SpringSecurity Jwt Token 自动刷新的实现是指在用户登录系统后,系统颁发给用户一个Token,后续访问系统的请求都需要带上这个Token,如果请求没有带上这个Token或者...
recommend-type

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

Spring Boot结合Spring Security和JWT(JSON Web Token)提供了一种高效且灵活的解决方案。本文将深入探讨如何使用这些技术来构建用户登录和权限认证系统。 首先,让我们了解这三个关键组件: 1. **Spring Boot**...
recommend-type

SpringCloud+SpringBoot+OAuth2+Spring Security+Redis实现的微服务统一认证授权.doc

SpringCloud+SpringBoot+OAuth2+Spring Security+Redis实现的微服务统一认证授权
recommend-type

SpringBoot+Spring Security+JWT实现RESTful Api权限控制的方法

在本文中,我们将探讨如何使用Spring Boot、Spring Security和JSON Web Tokens (JWT)来实现RESTful API的权限控制。Spring Boot简化了构建基于Spring的应用程序流程,而Spring Security则提供了强大的安全框架,JWT...
recommend-type

Vue实现iOS原生Picker组件:详细解析与实现思路

"Vue.js实现iOS原生Picker效果及实现思路解析" 在iOS应用中,Picker组件通常用于让用户从一系列选项中进行选择,例如日期、时间或者特定的值。Vue.js作为一个流行的前端框架,虽然原生不包含与iOS Picker完全相同的组件,但开发者可以通过自定义组件来实现类似的效果。本篇文章将详细介绍如何在Vue.js项目中创建一个模仿iOS原生Picker功能的组件,并分享实现这一功能的思路。 首先,为了创建这个组件,我们需要一个基本的DOM结构。示例代码中给出了一个基础的模板,包括一个外层容器`<div class="pd-select-item">`,以及两个列表元素`<ul class="pd-select-list">`和`<ul class="pd-select-wheel">`,分别用于显示选定项和可滚动的选择项。 ```html <template> <div class="pd-select-item"> <div class="pd-select-line"></div> <ul class="pd-select-list"> <li class="pd-select-list-item">1</li> </ul> <ul class="pd-select-wheel"> <li class="pd-select-wheel-item">1</li> </ul> </div> </template> ``` 接下来,我们定义组件的属性(props)。`data`属性是必需的,它应该是一个数组,包含了所有可供用户选择的选项。`type`属性默认为'cycle',可能用于区分不同类型的Picker组件,例如循环滚动或非循环滚动。`value`属性用于设置初始选中的值。 ```javascript props: { data: { type: Array, required: true }, type: { type: String, default: 'cycle' }, value: {} } ``` 为了实现Picker的垂直居中效果,我们需要设置CSS样式。`.pd-select-line`, `.pd-select-list` 和 `.pd-select-wheel` 都被设置为绝对定位,通过`transform: translateY(-50%)`使其在垂直方向上居中。`.pd-select-list` 使用`overflow:hidden`来隐藏超出可视区域的部分。 为了达到iOS Picker的3D滚动效果,`.pd-select-wheel` 设置了`transform-style: preserve-3d`,确保子元素在3D空间中保持其位置。`.pd-select-wheel-item` 的每个列表项都设置了`position:absolute`,并使用`backface-visibility:hidden`来优化3D变换的性能。 ```css .pd-select-line, .pd-select-list, .pd-select-wheel { position: absolute; left: 0; right: 0; top: 50%; transform: translateY(-50%); } .pd-select-list { overflow: hidden; } .pd-select-wheel { transform-style: preserve-3d; height: 30px; } .pd-select-wheel-item { white-space: nowrap; text-overflow: ellipsis; backface-visibility: hidden; position: absolute; top: 0px; width: 100%; overflow: hidden; } ``` 最后,为了使组件能够响应用户的滚动操作,我们需要监听触摸事件,更新选中项,并可能还需要处理滚动动画。这通常涉及到计算滚动位置,映射到数据数组,以及根据滚动方向调整可见项的位置。 总结来说,实现Vue.js中的iOS原生Picker效果,需要构建一个包含可滚动列表的自定义组件,通过CSS样式实现3D滚动效果,并通过JavaScript处理触摸事件来模拟Picker的行为。通过这种方式,开发者可以在Vue.js项目中创建出与iOS原生界面风格一致的用户交互体验。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【广度优先搜索】:Python面试中的系统化思维展现

![【广度优先搜索】:Python面试中的系统化思维展现](https://media.geeksforgeeks.org/wp-content/cdn-uploads/20200611200432/Top-10-System-Design-Interview-Questions-and-Answers.png) # 1. 广度优先搜索(BFS)算法概述 广度优先搜索(Breadth-First Search, BFS)算法是图论中的一种基本算法,广泛应用于计算机科学和工程领域。它是对树或图进行遍历的一种方法,按照距离起点的远近逐层进行搜索,直到找到目标节点或遍历完所有可到达的节点。这种算法
recommend-type

nginx ubuntu离线安装

Nginx是一款开源的高性能Web服务器和反向代理服务器,常用于Linux系统,如Ubuntu。离线安装通常指在没有网络连接的情况下本地获取并配置软件包。以下是Nginx在Ubuntu上离线安装的基本步骤: 1. **下载Nginx包**: - 首先,你需要从Nginx官方网站下载适用于Ubuntu的二进制包。访问 https://nginx.org/en/download.html ,选择对应版本的`nginx`文件,比如`nginxxx.x.tar.gz`,将其保存到你的离线环境中。 2. **解压并移动文件**: 使用`tar`命令解压缩下载的文件: ```
recommend-type

Arduino蓝牙小车:参数调试与功能控制

本资源是一份基于Arduino Mega2560主控的蓝牙遥控小车程序代码,适用于Android设备通过蓝牙进行操控。该程序允许车辆实现运动、显示和测温等多种功能,具有较高的灵活性和实用性。 1. **蓝牙通信与模块操作** 在程序开始时,开发者提醒用户在上传代码前需将蓝牙模块的RX接口暂时拔掉,上传成功后再恢复连接。这可能是因为在调试过程中,需要确保串口通信的纯净性。程序通过Serial.begin()函数设置串口波特率为9600,这是常见的蓝牙通信速率,适合于手机等设备连接。 2. **电机控制参数调整** 代码中提到的"偏转角度需要根据场地不同进行调参数",表明程序设计为支持自定义参数,通过宏变量的形式,用户可以根据实际需求对小车的转向灵敏度进行个性化设置。例如,`#define left_forward_PIN4` 和 `#define right_forward_PIN2` 定义了左右轮的前进控制引脚,这些引脚的输出值范围是1-255,允许通过编程精确控制轮速。 3. **行驶方向控制** 小车的行驶方向通过改变特定引脚的高低电平来实现。例如,`void left_forward_PIN4` 和 `void left_back_PIN5` 分别控制左轮前进和后退,用户可以通过赋予高或低电平来指示小车的行驶方向。同时,右轮的控制方式类似。 4. **多种移动模式** 除了基本的前进和后退,程序还提供了原地左转、原地右转、右前、左前、左后和右后的控制函数,如`void turnLeftOrigin()` 等,增强了小车的机动性和操作多样性。 5. **主函数和循环结构** 主函数`void setup()`用于初始化硬件,包括串口通信和引脚配置。而`void loop()`则是一个无限循环,通过`void reve()`函数不断接收并处理蓝牙发送的指令,保持小车持续响应用户的控制命令。 6. **数据接收与解析** `void reve()`函数通过`Serial.parseInt()`读取蓝牙发送的数字值(7在示例中被提及),然后根据接收到的指令执行相应的移动命令,体现了程序的核心逻辑部分。 总结来说,这份蓝牙小车程序代码为开发人员提供了一个基础平台,通过调整参数和编写特定的控制函数,能够实现不同场景下的小车控制,具有较强的通用性和可扩展性。对于学习和实践Arduino与蓝牙通信的开发者来说,这是一个很好的学习和实践案例。