Search in sources :

Example 1 with JWT

use of com.auth0.android.jwt.JWT in project Taier by DTStack.

the class TokenService method decryption.

public DTToken decryption(String tokenText) {
    Assert.notNull(tokenText, "JWT Token Text can't blank.");
    try {
        /**
         * 验证
         */
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(JWT_TOKEN)).build().verify(tokenText);
        DTToken token = new DTToken();
        token.setUserName(jwt.getClaim(DTToken.USER_NAME).asString());
        token.setUserId(Long.parseLong(jwt.getClaim(DTToken.USER_ID).asString()));
        if (!jwt.getClaim(DTToken.TENANT_ID).isNull()) {
            token.setTenantId(Long.parseLong(jwt.getClaim(DTToken.TENANT_ID).asString()));
        }
        token.setExpireAt(jwt.getExpiresAt());
        return token;
    } catch (UnsupportedEncodingException e) {
        if (log.isErrorEnabled()) {
            log.error("JWT Token decode Error.", e);
        }
        throw new RdosDefineException("DT Token解码异常.");
    } catch (TokenExpiredException e) {
        if (log.isErrorEnabled()) {
            log.error("JWT Token expire.", e);
        }
        throw new RdosDefineException("DT Token已过期");
    }
}
Also used : TokenExpiredException(com.auth0.jwt.exceptions.TokenExpiredException) RdosDefineException(com.dtstack.taier.common.exception.RdosDefineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DTToken(com.dtstack.taier.develop.dto.user.DTToken) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 2 with JWT

use of com.auth0.android.jwt.JWT in project Taier by DTStack.

the class TokenService method decryptionWithOutExpire.

public DTToken decryptionWithOutExpire(String tokenText) {
    Assert.notNull(tokenText, "JWT Token Text can't blank.");
    try {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(JWT_TOKEN)).build().verify(tokenText);
        DTToken token = new DTToken();
        token.setUserName(jwt.getClaim(DTToken.USER_NAME).asString());
        token.setUserId(Long.parseLong(jwt.getClaim(DTToken.USER_ID).asString()));
        if (!jwt.getClaim(DTToken.TENANT_ID).isNull()) {
            token.setTenantId(Long.parseLong(jwt.getClaim(DTToken.TENANT_ID).asString()));
        }
        return token;
    } catch (UnsupportedEncodingException e) {
        throw new RdosDefineException("DT Token解码异常.");
    }
}
Also used : RdosDefineException(com.dtstack.taier.common.exception.RdosDefineException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DTToken(com.dtstack.taier.develop.dto.user.DTToken) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 3 with JWT

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

the class AuthBuilderTest method shouldOverwriteClaimOnMultipleAddCalls.

@Test
public void shouldOverwriteClaimOnMultipleAddCalls() {
    String token = authBuilder.addClaim("test", 1L).addClaim("test", 2).addClaim("test", "foo").buildToken();
    DecodedJWT jwt = JWT.decode(token);
    assertThat(jwt.getClaim("test").asLong()).isNull();
    assertThat(jwt.getClaim("test").asInt()).isNull();
    assertThat(jwt.getClaim("test").asString()).isEqualTo("foo");
}
Also used : DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT) Test(org.junit.Test)

Example 4 with JWT

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

the class OpaAuthFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    Span span = tracer.buildSpan("authorizeUsingOpa").withTag("opa.allow", false).withTag(COMPONENT, "OpaAuthFilter").start();
    try (Scope ignored = tracer.scopeManager().activate(span)) {
        // collect input parameters for Opa request
        UriInfo uriInfo = requestContext.getUriInfo();
        String method = requestContext.getMethod();
        String trace = requestContext.getHeaderString(RequestTracing.TOKEN_HEADER);
        String jwt = null;
        // if security context already exist and if it is a jwt security context,
        // we include the jwt in the request
        SecurityContext securityContext = requestContext.getSecurityContext();
        Map<String, Claim> claims = null;
        if (null != securityContext) {
            JwtPrincipal jwtPrincipal = getJwtPrincipal(requestContext.getSecurityContext());
            if (jwtPrincipal != null) {
                // JWT principal found, this means that JWT has been validated by
                // auth bundle
                // and can be used within this bundle
                jwt = jwtPrincipal.getJwt();
                claims = jwtPrincipal.getClaims();
            }
        }
        JsonNode constraints = null;
        if (!isDisabled && !isExcluded(uriInfo)) {
            // process the actual request to the open policy agent server
            String[] path = uriInfo.getPathSegments().stream().map(PathSegment::getPath).toArray(String[]::new);
            OpaInput opaInput = new OpaInput(jwt, path, method, trace);
            ObjectNode objectNode = om.convertValue(opaInput, ObjectNode.class);
            // append the input extensions to the input object
            inputExtensions.forEach((namespace, extension) -> objectNode.set(namespace, om.valueToTree(extension.createAdditionalInputContent(requestContext))));
            OpaRequest request = OpaRequest.request(objectNode);
            constraints = authorizeWithOpa(request, span);
        }
        OpaJwtPrincipal principal = OpaJwtPrincipal.create(jwt, claims, constraints, om);
        replaceSecurityContext(requestContext, securityContext, principal);
    } finally {
        span.finish();
    }
}
Also used : OpaJwtPrincipal(org.sdase.commons.server.opa.OpaJwtPrincipal) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) JwtPrincipal(org.sdase.commons.server.auth.JwtPrincipal) OpaJwtPrincipal(org.sdase.commons.server.opa.OpaJwtPrincipal) JsonNode(com.fasterxml.jackson.databind.JsonNode) Span(io.opentracing.Span) Scope(io.opentracing.Scope) SecurityContext(javax.ws.rs.core.SecurityContext) OpaRequest(org.sdase.commons.server.opa.filter.model.OpaRequest) UriInfo(javax.ws.rs.core.UriInfo) Claim(com.auth0.jwt.interfaces.Claim) OpaInput(org.sdase.commons.server.opa.filter.model.OpaInput)

Example 5 with JWT

use of com.auth0.android.jwt.JWT in project gravitee-api-management by gravitee-io.

the class AbstractAuthenticationResource method connectUserInternal.

protected Response connectUserInternal(UserEntity user, final String state, final HttpServletResponse servletResponse, final String accessToken, final String idToken) {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    final UserDetails userDetails = (UserDetails) authentication.getPrincipal();
    // Manage authorities, initialize it with dynamic permissions from the IDP
    List<Map<String, String>> authorities = userDetails.getAuthorities().stream().map(authority -> Maps.<String, String>builder().put("authority", authority.getAuthority()).build()).collect(Collectors.toList());
    // We must also load permissions from repository for configured management or portal role
    Set<RoleEntity> userRoles = membershipService.getRoles(MembershipReferenceType.ORGANIZATION, GraviteeContext.getCurrentOrganization(), MembershipMemberType.USER, userDetails.getId());
    if (!userRoles.isEmpty()) {
        userRoles.forEach(role -> authorities.add(Maps.<String, String>builder().put("authority", role.getScope().toString() + ':' + role.getName()).build()));
    }
    // JWT signer
    Algorithm algorithm = Algorithm.HMAC256(environment.getProperty("jwt.secret"));
    Date issueAt = new Date();
    Instant expireAt = issueAt.toInstant().plus(Duration.ofSeconds(environment.getProperty("jwt.expire-after", Integer.class, DEFAULT_JWT_EXPIRE_AFTER)));
    final String token = JWT.create().withIssuer(environment.getProperty("jwt.issuer", DEFAULT_JWT_ISSUER)).withIssuedAt(issueAt).withExpiresAt(Date.from(expireAt)).withSubject(user.getId()).withClaim(JWTHelper.Claims.PERMISSIONS, authorities).withClaim(JWTHelper.Claims.EMAIL, user.getEmail()).withClaim(JWTHelper.Claims.FIRSTNAME, user.getFirstname()).withClaim(JWTHelper.Claims.LASTNAME, user.getLastname()).withJWTId(UUID.randomUUID().toString()).sign(algorithm);
    final TokenEntity tokenEntity = new TokenEntity();
    tokenEntity.setType(BEARER);
    tokenEntity.setToken(token);
    if (idToken != null) {
        tokenEntity.setAccessToken(accessToken);
        tokenEntity.setIdToken(idToken);
    }
    if (state != null && !state.isEmpty()) {
        tokenEntity.setState(state);
    }
    final Cookie bearerCookie = cookieGenerator.generate(TokenAuthenticationFilter.AUTH_COOKIE_NAME, "Bearer%20" + token);
    servletResponse.addCookie(bearerCookie);
    return Response.ok(tokenEntity).build();
}
Also used : JWT(com.auth0.jwt.JWT) java.util(java.util) NotBlank(javax.validation.constraints.NotBlank) BEARER(io.gravitee.rest.api.management.rest.model.TokenType.BEARER) Autowired(org.springframework.beans.factory.annotation.Autowired) GraviteeContext(io.gravitee.rest.api.service.common.GraviteeContext) Algorithm(com.auth0.jwt.algorithms.Algorithm) CookieGenerator(io.gravitee.rest.api.security.cookies.CookieGenerator) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity) UserService(io.gravitee.rest.api.service.UserService) Duration(java.time.Duration) TypeReference(com.fasterxml.jackson.core.type.TypeReference) Cookie(javax.servlet.http.Cookie) SecurityContextHolder(org.springframework.security.core.context.SecurityContextHolder) MembershipMemberType(io.gravitee.rest.api.model.MembershipMemberType) MembershipService(io.gravitee.rest.api.service.MembershipService) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Instant(java.time.Instant) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Collectors(java.util.stream.Collectors) Maps(io.gravitee.common.util.Maps) RoleEntity(io.gravitee.rest.api.model.RoleEntity) DEFAULT_JWT_ISSUER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_ISSUER) MembershipReferenceType(io.gravitee.rest.api.model.MembershipReferenceType) Response(javax.ws.rs.core.Response) TokenAuthenticationFilter(io.gravitee.rest.api.security.filter.TokenAuthenticationFilter) Environment(org.springframework.core.env.Environment) JWTHelper(io.gravitee.rest.api.service.common.JWTHelper) DEFAULT_JWT_EXPIRE_AFTER(io.gravitee.rest.api.service.common.JWTHelper.DefaultValues.DEFAULT_JWT_EXPIRE_AFTER) Authentication(org.springframework.security.core.Authentication) UserEntity(io.gravitee.rest.api.model.UserEntity) Cookie(javax.servlet.http.Cookie) Instant(java.time.Instant) Algorithm(com.auth0.jwt.algorithms.Algorithm) RoleEntity(io.gravitee.rest.api.model.RoleEntity) UserDetails(io.gravitee.rest.api.idp.api.authentication.UserDetails) Authentication(org.springframework.security.core.Authentication) TokenEntity(io.gravitee.rest.api.management.rest.model.TokenEntity)

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