Skip to content

Instantly share code, notes, and snippets.

@jeffersonchaves
Created July 7, 2025 18:56
Show Gist options
  • Save jeffersonchaves/67231e4319e9b6857d9e52ea35f1bbe6 to your computer and use it in GitHub Desktop.
Save jeffersonchaves/67231e4319e9b6857d9e52ea35f1bbe6 to your computer and use it in GitHub Desktop.
@Service
public class JwtService {
@Autowired
private JwtEncoder encoder;
public String generateToken(Authentication authentication) {
Instant now = Instant.now();
long expiry = 525600L;
String roles = authentication
.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors
.joining(" "));
JwtClaimsSet claims = JwtClaimsSet.builder()
.issuer("spring-security-jwt")
.issuedAt(now)
.expiresAt(now.plusSeconds(expiry))
.subject(authentication.getName())
.claim("scope", roles)
.build();
return encoder.encode(
JwtEncoderParameters.from(claims))
.getTokenValue();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment