Search in sources :

Example 36 with JWT

use of com.auth0.android.jwt.JWT in project restheart by SoftInstigate.

the class JwtAuthenticationMechanism method init.

@InjectConfiguration
public void init(Map<String, Object> args) throws ConfigurationException {
    // get configuration arguments
    base64Encoded = argValue(args, "base64Encoded");
    algorithm = argValue(args, "algorithm");
    key = argValue(args, "key");
    usernameClaim = argValue(args, "usernameClaim");
    rolesClaim = argValue(args, "rolesClaim");
    fixedRoles = argValue(args, "fixedRoles");
    issuer = argValue(args, "issuer");
    audience = argValue(args, "audience");
    Algorithm _algorithm;
    try {
        _algorithm = getAlgorithm(algorithm, key);
    } catch (CertificateException | UnsupportedEncodingException ex) {
        throw new ConfigurationException("wrong JWT configuration, " + "cannot setup algorithm", ex);
    }
    Verification v = JWT.require(_algorithm);
    if (audience != null) {
        v.withAudience(audience);
    }
    if (issuer != null) {
        v.withIssuer(issuer);
    }
    if (rolesClaim != null && fixedRoles != null) {
        throw new ConfigurationException("wrong JWT configuration, " + "cannot set both 'rolesClaim' and 'fixedRoles'");
    }
    if (rolesClaim == null && fixedRoles == null) {
        throw new ConfigurationException("wrong JWT configuration, " + "need to set either 'rolesClaim' or 'fixedRoles'");
    }
    this.jwtVerifier = v.build();
}
Also used : ConfigurationException(org.restheart.ConfigurationException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CertificateException(java.security.cert.CertificateException) Verification(com.auth0.jwt.interfaces.Verification) Algorithm(com.auth0.jwt.algorithms.Algorithm) InjectConfiguration(org.restheart.plugins.InjectConfiguration)

Example 37 with JWT

use of com.auth0.android.jwt.JWT in project bookmark by FleyX.

the class JwtUtil method encode.

/**
 * Description: 生成一个jwt字符串
 *
 * @param map     data携带数据
 * @param secret  秘钥
 * @param timeOut 超时时间(单位s)
 * @return java.lang.String
 * @author fanxb
 * @date 2019/3/4 17:26
 */
public static String encode(Map<String, String> map, String secret, long timeOut) {
    Algorithm algorithm = Algorithm.HMAC256(secret);
    JWTCreator.Builder builder = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + timeOut));
    // 设置负载
    map.forEach(builder::withClaim);
    return builder.sign(algorithm);
}
Also used : JWTCreator(com.auth0.jwt.JWTCreator) Algorithm(com.auth0.jwt.algorithms.Algorithm) Date(java.util.Date)

Example 38 with JWT

use of com.auth0.android.jwt.JWT in project ARLAS-server by gisaia.

the class AuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext ctx) {
    Transaction transaction = ElasticApm.currentTransaction();
    boolean isPublic = ctx.getUriInfo().getPath().concat(":").concat(ctx.getMethod()).matches(authConf.getPublicRegex());
    String header = ctx.getHeaderString(HttpHeaders.AUTHORIZATION);
    if (header == null || (header != null && !header.toLowerCase().startsWith("bearer "))) {
        if (isPublic || ctx.getMethod() == "OPTIONS") {
            return;
        } else {
            ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
    }
    try {
        // header presence and format already checked before in AuthenticationFilter
        DecodedJWT jwt = jwtVerifier.verify(header.substring(7));
        // remove it in case it's been set manually
        ctx.getHeaders().remove(authConf.headerUser);
        String userId = jwt.getSubject();
        if (!StringUtil.isNullOrEmpty(userId)) {
            ctx.getHeaders().putSingle(authConf.headerUser, userId);
            transaction.setUser(userId, "", "");
        }
        // remove it in case it's been set manually
        ctx.getHeaders().remove(authConf.headerGroup);
        Claim jwtClaimRoles = jwt.getClaim(authConf.claimRoles);
        if (!jwtClaimRoles.isNull()) {
            List<String> groups = jwtClaimRoles.asList(String.class).stream().filter(r -> r.toLowerCase().startsWith("group")).collect(Collectors.toList());
            ctx.setProperty("groups", groups);
            ctx.getHeaders().put(authConf.headerGroup, groups);
        }
        Claim jwtClaimPermissions = jwt.getClaim(authConf.claimPermissions);
        if (!jwtClaimPermissions.isNull()) {
            ArlasClaims arlasClaims = new ArlasClaims(jwtClaimPermissions.asList(String.class));
            ctx.setProperty("claims", arlasClaims);
            if (arlasClaims.isAllowed(ctx.getMethod(), ctx.getUriInfo().getPath())) {
                arlasClaims.injectHeaders(ctx.getHeaders(), transaction);
                return;
            }
        }
        if (isPublic) {
            return;
        } else {
            ctx.abortWith(Response.status(Response.Status.FORBIDDEN).build());
        }
    } catch (JWTVerificationException e) {
        LOGGER.warn("JWT verification failed.", e);
        if (!isPublic) {
            ctx.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
        }
        return;
    }
    ctx.abortWith(Response.status(Response.Status.FORBIDDEN).build());
}
Also used : X509Certificate(java.security.cert.X509Certificate) JWT(com.auth0.jwt.JWT) Transaction(co.elastic.apm.api.Transaction) StringUtil(io.arlas.server.core.utils.StringUtil) Provider(javax.ws.rs.ext.Provider) CertificateFactory(java.security.cert.CertificateFactory) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) URL(java.net.URL) LoggerFactory(org.slf4j.LoggerFactory) Priorities(javax.ws.rs.Priorities) ContainerRequestFilter(javax.ws.rs.container.ContainerRequestFilter) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) RSAPublicKey(java.security.interfaces.RSAPublicKey) JWTVerifier(com.auth0.jwt.interfaces.JWTVerifier) Claim(com.auth0.jwt.interfaces.Claim) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ArlasAuthConfiguration(io.arlas.server.core.app.ArlasAuthConfiguration) Logger(org.slf4j.Logger) ElasticApm(co.elastic.apm.api.ElasticApm) FileInputStream(java.io.FileInputStream) Collectors(java.util.stream.Collectors) Priority(javax.annotation.Priority) List(java.util.List) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) InputStream(java.io.InputStream) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) Transaction(co.elastic.apm.api.Transaction) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Claim(com.auth0.jwt.interfaces.Claim)

Example 39 with JWT

use of com.auth0.android.jwt.JWT in project drug-formulary-ri by HL7-DaVinci.

the class IntrospectionEndpoint method handleIntrospection.

public static ResponseEntity<String> handleIntrospection(String token) {
    JSONObject response = new JSONObject();
    String baseUrl = AuthUtils.getFhirBaseUrl();
    try {
        Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(baseUrl).withAudience(baseUrl).build();
        DecodedJWT jwt = verifier.verify(token);
        response.put("active", true);
        response.put("aud", jwt.getAudience().get(0));
        response.put("iss", jwt.getIssuer());
        // Display in sec not ms
        response.put("exp", jwt.getExpiresAt().getTime() / 1000);
        // Display in sec not ms
        response.put("iat", jwt.getIssuedAt().getTime() / 1000);
        response.put("patient_id", jwt.getClaim("patient_id").asString());
    } catch (JWTVerificationException exception) {
        response.put("active", false);
    }
    return new ResponseEntity<>(response.toString(), HttpStatus.OK);
}
Also used : JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) ResponseEntity(org.springframework.http.ResponseEntity) JSONObject(org.json.JSONObject) Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 40 with JWT

use of com.auth0.android.jwt.JWT in project drug-formulary-ri by HL7-DaVinci.

the class PatientAuthorizationInterceptor method verify.

/**
 * Helper method to verify and decode the access token
 *
 * @param token       - the access token
 * @param fhirBaseUrl - the base url of this FHIR server
 * @return the base interface Patient ID datatype if the jwt token is verified
 *         and contains a patient ID in it claim, otherwise null.
 * @throws SignatureVerificationException
 * @throws TokenExpiredException
 * @throws JWTVerificationException
 */
private IIdType verify(String token, String fhirBaseUrl) throws SignatureVerificationException, TokenExpiredException, JWTVerificationException {
    Algorithm algorithm = Algorithm.RSA256(OauthEndpointController.getPublicKey(), null);
    logger.fine("Verifying JWT token iss and aud is " + fhirBaseUrl);
    JWTVerifier verifier = JWT.require(algorithm).withIssuer(fhirBaseUrl).withAudience(fhirBaseUrl).build();
    DecodedJWT jwt = verifier.verify(token);
    String patientId = jwt.getClaim("patient_id").asString();
    if (patientId != null)
        return new IdType("Patient", patientId);
    return null;
}
Also used : Algorithm(com.auth0.jwt.algorithms.Algorithm) JWTVerifier(com.auth0.jwt.JWTVerifier) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) IIdType(org.hl7.fhir.instance.model.api.IIdType) IdType(org.hl7.fhir.r4.model.IdType)

Aggregations

DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)305 Test (org.junit.Test)217 Algorithm (com.auth0.jwt.algorithms.Algorithm)110 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)82 JWTVerifier (com.auth0.jwt.JWTVerifier)79 IOException (java.io.IOException)60 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)54 ECDSAAlgorithmTest (com.auth0.jwt.algorithms.ECDSAAlgorithmTest)53 Date (java.util.Date)50 Claim (com.auth0.jwt.interfaces.Claim)36 RSAPublicKey (java.security.interfaces.RSAPublicKey)34 ECPublicKey (java.security.interfaces.ECPublicKey)27 ECDSAKeyProvider (com.auth0.jwt.interfaces.ECDSAKeyProvider)26 HashMap (java.util.HashMap)25 JWTDecodeException (com.auth0.jwt.exceptions.JWTDecodeException)20 Instant (java.time.Instant)20 JsonObject (com.google.gson.JsonObject)19 ServletException (javax.servlet.ServletException)19 JWT (com.auth0.jwt.JWT)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)18