如何使用JWT在spring boot中获取Refresh Token

时间:2018-04-02 07:45:49

标签: spring-boot jwt

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

这是我的代码..

SpringSecurityConfiguration

 @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();

}

TokenController

@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);

}
}

JwtGenerator

@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));
}

JwtValidator

@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;
}

}

我正在传递用户名和密码来获取令牌。提前谢谢

1 个答案:

答案 0 :(得分:0)

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