public static String generateToken(SystemUser systemUser) { Map<String, Object> claims = new HashMap<>(); return doGenerateToken(claims, systemUser.getUser_job_number()); }
时间: 2024-04-07 11:27:58 浏览: 54
这是一个生成令牌(token)的方法,输入参数为一个 SystemUser 对象。该方法的主要作用是生成一个包含用户信息的令牌字符串,用于身份验证和授权等操作。具体来说,该方法通过将用户的工号作为令牌的一部分,生成一个 JWT(JSON Web Token),并将其返回给调用者。在生成 JWT 的过程中,该方法还可以向 JWT 中添加一些自定义的声明(claims),以便将更多的用户信息传递给服务端。返回的令牌字符串可以存储在客户端,用于后续的身份验证请求。
相关问题
@RestController public class LoginController { @Resource(name = "userServiceImpl") private IUserService userService; @RequestMapping(value = "/login/login", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> login(HttpRequest request, HttpServletResponse response) { return userService.login(request, response); } @RequestMapping(value = "/login/check", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> check(HttpServletRequest request, HttpServletResponse response) { Result<User> result = new Result<>(); String userId = SessionContext.get("user_id"); if (StringUtils.isEmpty(userId)) { Cookie loginTypeCookie = new Cookie("login_type", "0"); loginTypeCookie.setPath("/"); loginTypeCookie.setSecure(true); response.addCookie(loginTypeCookie); result.set("login_type", 0); } else { Cookie loginTypeCookie = new Cookie("login_type", "1"); loginTypeCookie.setPath("/"); loginTypeCookie.setSecure(true); response.addCookie(loginTypeCookie); result.set("login_type", 1); result.set("user_id", SessionContext.get("user_id")); result.set("user_name", SessionContext.get("user_name")); result.set("login_name", SessionContext.get("login_name")); result.set("user_image_id", SessionContext.get("user_image_id")); result.set("role_type", SessionContext.get("role_type")); // 检查token 是否需要更新 HttpSession session = request.getSession(false); if(session != null){ // 更新 session String issueAtStr = SessionContext.get("issueAt"); if(StringUtils.isNotEmpty(issueAtStr)){ Date issueAt = DateUtils.stringToDate(issueAtStr, DateConst.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS_SSS); if(issueAt != null && TokenUtils.shouldTokenRefresh(issueAt)){ Map<String, Object> claims = new HashMap<>(10); claims.put("user_id", String.valueOf(SessionContext.getInt("user_id"))); claims.put("user_name", SessionContext.get("user_name")); claims.put("login_name", SessionContext.get("login_name")); claims.put("user_image_id", SessionContext.get("user_image_id")); claims.put("role_type", String.valueOf(SessionContext.getInt("role_type"))); String token = TokenUtils.createToken(claims); session.setAttribute("token", token); result.set("token", token); Cookie tokenCookie = new Cookie("token", token); tokenCookie.setPath("/"); response.addCookie(tokenCookie); } } } } return result; } @RequestMapping(value = "/login/exit", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"}) public Result<User> exit(HttpRequest request) { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } return new Result<>(); } }
){ // 计算过期时间,过期时间不足半小时 更新 token long expireTime = issueAt.getTime() + (30 * 60 * 1000); // 过期时间为发放时间+30分钟 if(System.currentTimeMillis() >= expireTime){ // 需要更新 token String token = JWTUtils.createToken(SessionContext.get("user_id")); session.setAttribute("token", token); result.set("token", token); } } } } } return result; } }
请问这段代码实现了什么功能?
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; }
首先需要引入相关的依赖,包括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并返回给前端。
阅读全文