gpt4 book ai didi

spring-boot - 如何使用 JWT 在 Spring Boot 中获取刷新 token

转载 作者:行者123 更新时间:2023-12-04 11:53:26 27 4
gpt4 key购买 nike

我正在使用 JWT 为 REST API 做 spring 安全。我已经完成了创建具有到期时间且工作正常的网络 token 。我已将时间限制设置为 5 分钟。 5 分钟后, token 将过期。这给我带来了问题,所以任何人都可以指导我如何使用刷新 token 来解决这个问题,因为我对这个概念很陌生。

这是我的代码..

SpringSecurity配置

 @Bean
public JwtAuthenticationTokenFilter authenticationTokenFilter() {
JwtAuthenticationTokenFilter filter = new
JwtAuthenticationTokenFilter();
filter.setAuthenticationManager(authenticationManager());
filter.setAuthenticationSuccessHandler(new JwtSuccessHandler());
return filter;
}


@Override
protected void configure(HttpSecurity http) throws Exception {

http.csrf().disable()
.authorizeRequests().antMatchers("/admin/**").authenticated()
.antMatchers("/admin/**").hasAnyAuthority("Admin")
.and()
.exceptionHandling().authenticationEntryPoint(entryPoint)
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();

}

token Controller
@RestController
@RequestMapping("/token")
public class TokenController {

private JwtGenerator jwtGenerator;

public TokenController(JwtGenerator jwtGenerator) {
this.jwtGenerator = jwtGenerator;
}

@RequestMapping(method = RequestMethod.POST)
public String generate(@RequestBody final User user) {

return jwtGenerator.generate(user);

}
}

Jwt生成器
@Component
public class JwtGenerator {
private Long expiration;
private String secret = "youtube";
static final String CLAIM_KEY_CREATED = "created";

public String generate(User user) {
Claims claims = Jwts.claims()
.setSubject(user.getFirstName());
claims.put("password", String.valueOf(user.getPassword()));
//claims.put("role", jwtUser.getRole());

return Jwts.builder()
.setClaims(claims)
.setExpiration(generateExpirationDate())
.signWith(SignatureAlgorithm.HS512, "youtube")
.compact();
}

private Date generateExpirationDate() {
return new Date(System.currentTimeMillis() + (5 * 60 * 1000));
}
}

JwtAuthenticationProvider
@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken) throws AuthenticationException {

JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) usernamePasswordAuthenticationToken;
String token = jwtAuthenticationToken.getToken();

User user = validator.validate(token);

if (user == null) {
throw new RuntimeException("JWT Token is incorrect");
}
String firstname=user.getFirstName();
User user1=userRepository.getRoleId(firstname);
List<GrantedAuthority> grantedAuthorities = AuthorityUtils
.commaSeparatedStringToAuthorityList(user1.getRole().getRoleName());
return new JwtUserDetails(user.getFirstName(), user.getPassword(),
token,
grantedAuthorities);
}

@Override
public boolean supports(Class<?> aClass) {
return (JwtAuthenticationToken.class.isAssignableFrom(aClass));
}

验证器
@Component
public class JwtValidator {


private String secret = "youtube";

public User validate(String token) {

User user = null;
try {
Claims body = Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();

user = new User();
user.setFirstName(body.getSubject());
user.setPassword((String) body.get("password"));
//user.setRole((String) body.get("role"));
}
catch (Exception e) {
System.out.println(e);
}

return user;
}

}

我正在传递用户名和密码以获取 token 。提前致谢

最佳答案

您可能需要更改一点现有的解决方案。通常,您必须在成功授权后返回 2 个 JWT token - 一个“访问”JWT token 用于任何其他授权的服务器请求,以及“刷新”JWT token ,用于在第一个过期时检索新的“访问”JWT token .这也意味着您需要更改/修改/拦截应用程序的前端部分才能应用这些规则。好点是我在这里JWT Authentication Tutorial - An example using Spring Boot .

关于spring-boot - 如何使用 JWT 在 Spring Boot 中获取刷新 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49607309/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com