Skip to content

JWT Token #14

Open
Open
@hazartilirot

Description

Well, I'm not positive about issuing JWT to a user who has been just signed up regardless of error:

To my mind we need to get a token and only then submit a profile to our database

 public ResponseEntity<?> registerCustomer(
            @Valid @RequestBody CustomerDto customerDto
    ) {
        var token = jwtUtil.issueToken(customerDto.email(), "ROLE_USER");
        
        customerService.addCustomer(customerDto);

        return ResponseEntity.ok()
                             .header(HttpHeaders.AUTHORIZATION, token)
                             .build();
    }

then I suggest add a couple of extra lines into your application.yml file

jwt:
  token:
    expires:
      minutes: 60
  secret:
    key: placewhateverkeyyoulikebutmakesureitislongenough_placewhateverkeyyoulikebutmakesureitislongenough_placewhateverkeyyoulikebutmakesureitislongenough_

and here is my jwtUtil.java

@Service
public class JwtUtil {

    private final Environment env;

    public JwtUtil(Environment env) {
        this.env = env;
    }

    public String issueToken(String subject) {
        return issueToken(subject, Map.of());
    }

    public String issueToken(String subject, String ...scopes) {
        return issueToken(subject, Map.of("scopes", scopes));
    }

    public String issueToken(
            String subject,
            Map<String, Object> claims
    ) {
        var currentTime = LocalDateTime.now();
        var expiredWithinMinutes = Integer.parseInt(Objects.requireNonNull(env.getProperty("jwt.token.expires.minutes")));

        return Jwts
                .builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(Date.from(currentTime.atZone(ZoneId.systemDefault()).toInstant()))
                .setExpiration(Date.from(currentTime.plusMinutes(expiredWithinMinutes).atZone(ZoneId.systemDefault()).toInstant()))
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }

    private Key getSigningKey() {
        var secretInBytes = Objects.requireNonNull(env.getProperty("jwt.secret.key")).getBytes();

        byte[] bytesEncoded = Base64.getEncoder().encode(secretInBytes);
        return Keys.hmacShaKeyFor(bytesEncoded);
    }

}

I would also recommend installing Spring CLI, then creating a keystore like :
keytool -genkeypair -alias myKeyAlias -keyalg RSA \ -dname "CN=Local,OU=Local,O=My laptop,L=Hyderabad,S=Telangana,C=India" \ -keypass keyPassword -keystore server.jks -storepass storePassword

then encrypt our secret and use {cipher} instead.... but why bother?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions