Search in sources :

Example 96 with Claim

use of com.auth0.android.jwt.Claim in project structr by structr.

the class JWTHelper method getUserForAccessTokenWithSecret.

private static Principal getUserForAccessTokenWithSecret(String token, PropertyKey<String> eMailKey) throws FrameworkException {
    final String secret = Settings.JWTSecret.getValue();
    Map<String, Claim> claims = validateTokenWithSecret(token, secret);
    if (claims == null) {
        return null;
    }
    Principal user = getPrincipalForTokenClaims(claims, eMailKey);
    if (user == null) {
        return null;
    }
    // Check if the access_token is still valid.
    // If access_token isn't valid anymore, then either it timed out, or the user logged out.
    String tokenReference = claims.getOrDefault("tokenId", new NullClaim()).asString();
    if (validateTokenForUser(tokenReference, user)) {
        return user;
    }
    return null;
}
Also used : NullClaim(com.auth0.jwt.impl.NullClaim) NullClaim(com.auth0.jwt.impl.NullClaim) Claim(com.auth0.jwt.interfaces.Claim) Principal(org.structr.core.entity.Principal)

Example 97 with Claim

use of com.auth0.android.jwt.Claim in project structr by structr.

the class JWTHelper method getPrincipalForTokenClaims.

private static Principal getPrincipalForTokenClaims(Map<String, Claim> claims, PropertyKey<String> eMailKey) throws FrameworkException {
    final String instanceName = Settings.InstanceName.getValue();
    Principal user = null;
    String instance = claims.getOrDefault("instance", new NullClaim()).asString();
    String uuid = claims.getOrDefault("uuid", new NullClaim()).asString();
    String eMail = claims.getOrDefault("eMail", new NullClaim()).asString();
    if (StringUtils.isEmpty(eMail)) {
        eMail = claims.getOrDefault("email", new NullClaim()).asString();
    }
    // if the instance is the same that issued the token, we can lookup the user with uuid claim
    if (StringUtils.equals(instance, instanceName)) {
        user = StructrApp.getInstance().nodeQuery(Principal.class).and().or(NodeInterface.id, uuid).disableSorting().getFirst();
    } else if (eMail != null && StringUtils.isNotEmpty(eMail)) {
        user = StructrApp.getInstance().nodeQuery(Principal.class).and().or(eMailKey, eMail).disableSorting().getFirst();
    }
    return user;
}
Also used : NullClaim(com.auth0.jwt.impl.NullClaim) Principal(org.structr.core.entity.Principal)

Example 98 with Claim

use of com.auth0.android.jwt.Claim in project mycore by MyCoRe-Org.

the class MCRSessionFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    LOGGER.debug("Filter start.");
    boolean isSecure = requestContext.getSecurityContext().isSecure();
    if (MCRSessionMgr.hasCurrentSession()) {
        throw new InternalServerErrorException("Session is already attached.");
    }
    MCRSessionMgr.unlock();
    // bind to this request
    MCRSession currentSession = MCRSessionMgr.getCurrentSession();
    currentSession.setCurrentIP(MCRFrontendUtil.getRemoteAddr(httpServletRequest));
    MCRTransactionHelper.beginTransaction();
    // 3 cases for authentication
    Optional<MCRUserInformation> userInformation = Optional.empty();
    String authorization = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    // 1. no authentication
    if (authorization == null) {
        LOGGER.debug("No 'Authorization' header");
        return;
    }
    // 2. Basic Authentification
    String basicPrefix = "Basic ";
    if (authorization.startsWith(basicPrefix)) {
        LOGGER.debug("Using 'Basic' authentication.");
        byte[] encodedAuth = authorization.substring(basicPrefix.length()).trim().getBytes(StandardCharsets.ISO_8859_1);
        String userPwd = new String(Base64.getDecoder().decode(encodedAuth), StandardCharsets.ISO_8859_1);
        if (userPwd.contains(":") && userPwd.length() > 1) {
            String[] upSplit = userPwd.split(":");
            String username = upSplit[0];
            String password = upSplit[1];
            userInformation = Optional.ofNullable(MCRUserManager.checkPassword(username, password)).map(MCRUserInformation.class::cast).map(Optional::of).orElseThrow(() -> {
                LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
                attrs.put("error", "invalid_login");
                attrs.put("error_description", "Wrong login or password.");
                return new NotAuthorizedException(Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, MCRRestAPIUtil.getWWWAuthenticateHeader(null, attrs, app)).build());
            });
        }
    }
    // 3. JWT
    String bearerPrefix = "Bearer ";
    if (authorization.startsWith(bearerPrefix)) {
        LOGGER.debug("Using 'JSON Web Token' authentication.");
        // get JWT
        String token = authorization.substring(bearerPrefix.length()).trim();
        // validate against secret
        try {
            DecodedJWT jwt = JWT.require(MCRJWTUtil.getJWTAlgorithm()).build().verify(token);
            // validate ip
            checkIPClaim(jwt.getClaim(MCRJWTUtil.JWT_CLAIM_IP), MCRFrontendUtil.getRemoteAddr(httpServletRequest));
            // validate in audience
            Optional<String> audience = jwt.getAudience().stream().filter(s -> MCRJWTResource.AUDIENCE.equals(s) || MCRRestAPIAuthentication.AUDIENCE.equals(s)).findAny();
            if (audience.isPresent()) {
                switch(audience.get()) {
                    case MCRJWTResource.AUDIENCE:
                        MCRJWTResource.validate(token);
                        break;
                    case MCRRestAPIAuthentication.AUDIENCE:
                        requestContext.setProperty(PROP_RENEW_JWT, true);
                        MCRRestAPIAuthentication.validate(token);
                        break;
                    default:
                        LOGGER.warn("Cannot validate JWT for '{}' audience.", audience.get());
                }
            }
            userInformation = Optional.of(new MCRJWTUserInformation(jwt));
            if (!ALLOWED_JWT_SESSION_ATTRIBUTES.isEmpty()) {
                for (Map.Entry<String, Claim> entry : jwt.getClaims().entrySet()) {
                    if (entry.getKey().startsWith(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX)) {
                        final String key = entry.getKey().substring(MCRJWTUtil.JWT_SESSION_ATTRIBUTE_PREFIX.length());
                        for (String prefix : ALLOWED_JWT_SESSION_ATTRIBUTES) {
                            if (key.startsWith(prefix)) {
                                currentSession.put(key, entry.getValue().asString());
                                break;
                            }
                        }
                    }
                }
            }
        } catch (JWTVerificationException e) {
            LOGGER.error(e.getMessage());
            LinkedHashMap<String, String> attrs = new LinkedHashMap<>();
            attrs.put("error", "invalid_token");
            attrs.put("error_description", e.getMessage());
            throw new NotAuthorizedException(e.getMessage(), e, MCRRestAPIUtil.getWWWAuthenticateHeader("Bearer", attrs, app));
        }
    }
    if (userInformation.isEmpty()) {
        LOGGER.warn(() -> "Unsupported " + HttpHeaders.AUTHORIZATION + " header: " + authorization);
    }
    userInformation.ifPresent(ui -> {
        currentSession.setUserInformation(ui);
        requestContext.setSecurityContext(new MCRRestSecurityContext(ui, isSecure));
    });
    LOGGER.info("user detected: " + currentSession.getUserInformation().getUserID());
}
Also used : JWT(com.auth0.jwt.JWT) Arrays(java.util.Arrays) Context(jakarta.ws.rs.core.Context) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) MCRUser(org.mycore.user2.MCRUser) MCRRestAPIAuthentication(org.mycore.restapi.v1.MCRRestAPIAuthentication) LinkedHashMap(java.util.LinkedHashMap) Response(jakarta.ws.rs.core.Response) SecurityContext(jakarta.ws.rs.core.SecurityContext) MCRJWTUtil(org.mycore.frontend.jersey.MCRJWTUtil) ContainerRequestFilter(jakarta.ws.rs.container.ContainerRequestFilter) Map(java.util.Map) ContainerResponseContext(jakarta.ws.rs.container.ContainerResponseContext) ContainerResponseFilter(jakarta.ws.rs.container.ContainerResponseFilter) Priority(jakarta.annotation.Priority) MCRTransactionHelper(org.mycore.common.MCRTransactionHelper) Claim(com.auth0.jwt.interfaces.Claim) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) MCRUserInformation(org.mycore.common.MCRUserInformation) CacheControl(jakarta.ws.rs.core.CacheControl) NotAuthorizedException(jakarta.ws.rs.NotAuthorizedException) MCRConfiguration2(org.mycore.common.config.MCRConfiguration2) IOException(java.io.IOException) MCRUserManager(org.mycore.user2.MCRUserManager) MCRFrontendUtil(org.mycore.frontend.MCRFrontendUtil) Provider(jakarta.ws.rs.ext.Provider) UnknownHostException(java.net.UnknownHostException) Collectors(java.util.stream.Collectors) ProxyOutputStream(org.apache.commons.io.output.ProxyOutputStream) StandardCharsets(java.nio.charset.StandardCharsets) Priorities(jakarta.ws.rs.Priorities) RuntimeDelegate(jakarta.ws.rs.ext.RuntimeDelegate) MCRJWTResource(org.mycore.frontend.jersey.resources.MCRJWTResource) Base64(java.util.Base64) List(java.util.List) Principal(java.security.Principal) Logger(org.apache.logging.log4j.Logger) MCRSystemUserInformation(org.mycore.common.MCRSystemUserInformation) ContainerRequestContext(jakarta.ws.rs.container.ContainerRequestContext) MCRSession(org.mycore.common.MCRSession) MCRRestAPIUtil(org.mycore.restapi.v1.utils.MCRRestAPIUtil) HttpHeaders(jakarta.ws.rs.core.HttpHeaders) MCRSessionMgr(org.mycore.common.MCRSessionMgr) Optional(java.util.Optional) Application(jakarta.ws.rs.core.Application) LogManager(org.apache.logging.log4j.LogManager) Optional(java.util.Optional) NotAuthorizedException(jakarta.ws.rs.NotAuthorizedException) LinkedHashMap(java.util.LinkedHashMap) JWTVerificationException(com.auth0.jwt.exceptions.JWTVerificationException) MCRSession(org.mycore.common.MCRSession) InternalServerErrorException(jakarta.ws.rs.InternalServerErrorException) MCRUserInformation(org.mycore.common.MCRUserInformation) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Claim(com.auth0.jwt.interfaces.Claim)

Example 99 with Claim

use of com.auth0.android.jwt.Claim in project sda-dropwizard-commons by SDA-SE.

the class AuthBuilderTest method shouldAddStringClaim.

@Test
public void shouldAddStringClaim() {
    String token = authBuilder.addClaim("testKey", "hello").buildToken();
    Claim claim = JWT.decode(token).getClaim("testKey");
    assertThat(claim.asString()).isEqualTo("hello");
}
Also used : Claim(com.auth0.jwt.interfaces.Claim) Test(org.junit.Test)

Example 100 with Claim

use of com.auth0.android.jwt.Claim in project sda-dropwizard-commons by SDA-SE.

the class AuthBuilderTest method shouldAddLongClaim.

@Test
public void shouldAddLongClaim() {
    String token = authBuilder.addClaim("testKey", 2L + Integer.MAX_VALUE).buildToken();
    Claim claim = JWT.decode(token).getClaim("testKey");
    assertThat(claim.asLong()).isEqualTo(2147483649L);
}
Also used : Claim(com.auth0.jwt.interfaces.Claim) Test(org.junit.Test)

Aggregations

Claim (com.auth0.jwt.interfaces.Claim)110 Test (org.junit.Test)67 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)62 JsonNode (com.fasterxml.jackson.databind.JsonNode)42 Algorithm (com.auth0.jwt.algorithms.Algorithm)24 Date (java.util.Date)24 JWTVerificationException (com.auth0.jwt.exceptions.JWTVerificationException)21 RSAPublicKey (java.security.interfaces.RSAPublicKey)21 Test (org.junit.jupiter.api.Test)18 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)17 JWTVerifier (com.auth0.jwt.JWTVerifier)15 JwksTestKeySource (org.sdase.commons.server.auth.service.testsources.JwksTestKeySource)14 JsonObject (com.google.gson.JsonObject)10 HashMap (java.util.HashMap)9 UserPojo (com.auth0.jwt.UserPojo)8 IOException (java.io.IOException)8 Map (java.util.Map)8 TestingProcessManager (io.supertokens.test.TestingProcessManager)7 NullClaim (com.auth0.jwt.impl.NullClaim)5 JWT (com.auth0.jwt.JWT)4