All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.scalecube.security.jwt.DefaultJwtAuthenticator Maven / Gradle / Ivy

There is a newer version: 1.0.33.rc1
Show newest version
package io.scalecube.security.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Header;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.scalecube.security.api.Profile;
import java.util.Map;
import reactor.core.publisher.Mono;

public final class DefaultJwtAuthenticator implements JwtAuthenticator {

  private final JwtKeyResolver jwtKeyResolver;

  public DefaultJwtAuthenticator(JwtKeyResolver jwtKeyResolver) {
    this.jwtKeyResolver = jwtKeyResolver;
  }

  @Override
  public Mono authenticate(String token) {
    return Mono.defer(() -> authenticate0(token)).onErrorMap(AuthenticationException::new);
  }

  private Mono authenticate0(String token) {
    String tokenWithoutSignature = token.substring(0, token.lastIndexOf(".") + 1);

    JwtParser parser = Jwts.parser();

    Jwt claims = parser.parseClaimsJwt(tokenWithoutSignature);

    return jwtKeyResolver
        .resolve((Map) claims.getHeader())
        .map(key -> parser.setSigningKey(key).parseClaimsJws(token).getBody())
        .map(this::profileFromClaims);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy