Search in sources :

Example 6 with JWT

use of com.auth0.jwt.JWT in project DragonProxy by DragonetMC.

the class LoginChainDecoder method decode.

/**
 * decode the chain data in Login packet for MCPE Note: the credit of this
 * function goes to Nukkit development team
 */
public void decode() {
    Map<String, List<String>> map = gson.fromJson(new String(this.chainJWT, StandardCharsets.UTF_8), new TypeToken<Map<String, List<String>>>() {
    }.getType());
    if (map.isEmpty() || !map.containsKey("chain") || map.get("chain").isEmpty())
        return;
    List<DecodedJWT> chainJWTs = new ArrayList<>();
    // Add the JWT tokens to a chain
    for (String token : map.get("chain")) chainJWTs.add(JWT.decode(token));
    DecodedJWT clientJWT = null;
    if (this.clientDataJWT != null) {
        clientJWT = JWT.decode(new String(this.clientDataJWT, StandardCharsets.UTF_8));
        chainJWTs.add(clientJWT);
    }
    // first step, check if the public provided key can decode the received chain
    try {
        ECPublicKey prevPublicKey = null;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            String encodedPublicKey = null;
            ECPublicKey publicKey = null;
            if (payload.has("identityPublicKey")) {
                encodedPublicKey = payload.get("identityPublicKey").getAsString();
                publicKey = (ECPublicKey) EC_KEY_FACTORY.generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(encodedPublicKey)));
            }
            // Trust the root ca public key and use it to verify the chain
            if (ENCODED_ROOT_CA_KEY.equals(encodedPublicKey) && payload.has("certificateAuthority") && payload.get("certificateAuthority").getAsBoolean()) {
                prevPublicKey = publicKey;
                continue;
            }
            // This will happen if the root ca key we have does not match the one presented by the client chain
            if (prevPublicKey == null)
                throw new NullPointerException("No trusted public key found in chain, is the client logged in or cracked");
            // Throws a SignatureVerificationException if the verification failed
            Algorithm.ECDSA384(prevPublicKey, null).verify(jwt);
            // Verification was successful since no exception was thrown
            // Set the previous public key to this one so that it can be used
            // to verify the next JWT token in the chain
            prevPublicKey = publicKey;
        }
        // The for loop successfully verified all JWT tokens with no exceptions thrown
        this.loginVerified = true;
        Logger.getLogger(this.getClass().getSimpleName()).info("The LoginPacket has been successfully verified for integrity");
    } catch (Exception e) {
        this.loginVerified = false;
        Logger.getLogger(this.getClass().getSimpleName()).info("Failed to verify the integrity of the LoginPacket");
        e.printStackTrace();
    }
    // This is in its own for loop due to the possibility that the chain verification failed
    for (DecodedJWT jwt : chainJWTs) {
        JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
        // Get the information we care about - The UUID and display name
        if (payload.has("extraData") && !payload.has("certificateAuthority")) {
            extraData = payload.get("extraData").getAsJsonObject();
            if (extraData.has("displayName"))
                this.username = extraData.get("displayName").getAsString();
            if (extraData.has("identity"))
                this.clientUniqueId = UUID.fromString(extraData.get("identity").getAsString());
            break;
        }
    }
    // debug purpose
    if (log_profiles_files) {
        try {
            BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".rawChainJTW"));
            writer1.write(getChainJWT());
            writer1.close();
            BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + ".rawClientDataJTW"));
            writer.write(getClientDataJWT());
            writer.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // debug purpose
        int index = 0;
        for (DecodedJWT jwt : chainJWTs) {
            JsonObject payload = gson.fromJson(new String(Base64.getDecoder().decode(jwt.getPayload())), JsonObject.class);
            try {
                BufferedWriter writer = new BufferedWriter(new FileWriter("logs/" + username + "_" + index + ".decodedChain"));
                writer.write(payload.toString());
                writer.close();
                index++;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    // client data & skin
    if (clientJWT != null) {
        this.clientData = gson.fromJson(new String(Base64.getDecoder().decode(clientJWT.getPayload()), StandardCharsets.UTF_8), JsonObject.class);
        // debug purpose
        if (log_profiles_files) {
            try {
                BufferedWriter writer1 = new BufferedWriter(new FileWriter("logs/" + username + ".decodedData"));
                writer1.write(this.clientData.toString());
                writer1.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        if (this.clientData.has("ClientRandomId"))
            this.clientId = this.clientData.get("ClientRandomId").getAsLong();
        if (this.clientData.has("SkinData") && this.clientData.has("SkinId")) {
            this.skin = new Skin(this.clientData.get("SkinData").getAsString(), this.clientData.get("SkinId").getAsString());
            if (this.clientData.has("CapeData"))
                this.skin.setCape(this.skin.new Cape(Base64.getDecoder().decode(this.clientData.get("CapeData").getAsString())));
        } else
            this.skin = Skin.DEFAULT_SKIN_STEVE;
        if (this.clientData.has("SkinGeometryName"))
            this.skinGeometryName = this.clientData.get("SkinGeometryName").getAsString();
        if (this.clientData.has("SkinGeometry"))
            this.skinGeometry = Base64.getDecoder().decode(this.clientData.get("SkinGeometry").getAsString());
    }
}
Also used : FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) X509EncodedKeySpec(java.security.spec.X509EncodedKeySpec) BufferedWriter(java.io.BufferedWriter) ECPublicKey(java.security.interfaces.ECPublicKey) TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) List(java.util.List) Skin(org.dragonet.common.data.entity.Skin) DecodedJWT(com.auth0.jwt.interfaces.DecodedJWT)

Example 7 with JWT

use of com.auth0.jwt.JWT in project nextprot-api by calipho-sib.

the class NextprotAuthProvider method authenticate.

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String token = ((Auth0JWTToken) authentication).getJwt();
    this.logger.debug("Trying to authenticate with token: " + token);
    try {
        Map<String, Object> map = null;
        Auth0User auth0User = null;
        // Should put this in 2 different providers
        if (token.split("\\.").length == 3) {
            // it's the id token (JWT)
            map = jwtVerifier.verify(token);
            this.logger.debug("Authenticating with JWT");
        }
        /* else { // not using access token for now
				try {
					
					this.logger.debug("Will ask auth0 service");
					
					//in case we send the access token
					auth0User = nextprotAuth0Endpoint.fetchUser(token);
					this.logger.debug("Authenticating with access token (asking auth0 endpoint)" + auth0User);
					
				}catch (Exception e){
					e.printStackTrace();
					this.logger.error(e.getMessage());
					throw new SecurityException("client id not found");
				}
			}*/
        this.logger.debug("Decoded JWT token" + map);
        UserDetails userDetails;
        // UI Widget map
        if ((auth0User != null && auth0User.getEmail() != null) || (map != null && map.containsKey("email"))) {
            String username = null;
            if (auth0User != null && auth0User.getEmail() != null) {
                username = auth0User.getEmail();
            } else {
                username = (String) map.get("email");
            }
            if (username != null) {
                userDetails = userDetailsService.loadUserByUsername(username);
                authentication.setAuthenticated(true);
                return createSuccessAuthentication(userDetails, map);
            } else
                return null;
        } else // Codec map
        if (map != null && map.containsKey("payload")) {
            Map<String, Object> payload = codec.decodeJWT(token);
            String username = (String) payload.get("email");
            if (username != null) {
                userDetails = userDetailsService.loadUserByUsername(username);
                userDetails.getAuthorities().clear();
                List<String> auths = (List<String>) payload.get("authorities");
                for (String authority : auths) {
                    ((Set<GrantedAuthority>) userDetails.getAuthorities()).add(new SimpleGrantedAuthority(authority));
                }
                authentication.setAuthenticated(true);
                return createSuccessAuthentication(userDetails, map);
            } else {
                return null;
            }
        } else
            throw new SecurityException("client id not found");
    /*//TODO add the application here or as another provider else if (map.containsKey("app_id")) {
				long appId = (Long) map.get("app_id");
				UserApplication userApp = userApplicationService.getUserApplication(appId);
				if (userApp.hasUserDataAccess()) {

					userDetails = userDetailsService.loadUserByUsername(userApp.getOwner());
					if (userDetails == null) {
						userService.createUser(buildUserFromAuth0(map));
					}
					userDetails = userDetailsService.loadUserByUsername(userApp.getOwner());
				}
			}*/
    } catch (InvalidKeyException e) {
        // this.logger.error("InvalidKeyException thrown while decoding JWT token " + e.getLocalizedMessage());
        throw new Auth0TokenException(e);
    } catch (NoSuchAlgorithmException e) {
        // this.logger.error("NoSuchAlgorithmException thrown while decoding JWT token " + e.getLocalizedMessage());
        throw new Auth0TokenException(e);
    } catch (IllegalStateException e) {
        // this.logger.error("IllegalStateException thrown while decoding JWT token " + e.getLocalizedMessage());
        throw new Auth0TokenException(e);
    } catch (SignatureException e) {
        // this.logger.error("SignatureException thrown while decoding JWT token " + e.getLocalizedMessage());
        throw new Auth0TokenException(e);
    } catch (IOException e) {
        // this.logger.error("IOException thrown while decoding JWT token " + e.getLocalizedMessage());
        throw new Auth0TokenException("invalid token", e);
    }
}
Also used : SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) GrantedAuthority(org.springframework.security.core.GrantedAuthority) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) Auth0TokenException(com.auth0.spring.security.auth0.Auth0TokenException) SimpleGrantedAuthority(org.springframework.security.core.authority.SimpleGrantedAuthority) Auth0User(com.auth0.Auth0User) UserDetails(org.springframework.security.core.userdetails.UserDetails) Auth0JWTToken(com.auth0.spring.security.auth0.Auth0JWTToken) List(java.util.List) Map(java.util.Map)

Example 8 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2ResourceServerBeanDefinitionParserTests method requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage.

@Test
public void requestWhenCustomJwtValidatorFailsThenCorrespondingErrorMessage() throws Exception {
    this.spring.configLocations(xml("MockJwtValidator"), xml("Jwt")).autowire();
    mockRestOperations(jwks("Default"));
    String token = this.token("ValidNoScopes");
    OAuth2TokenValidator<Jwt> jwtValidator = this.spring.getContext().getBean(OAuth2TokenValidator.class);
    OAuth2Error error = new OAuth2Error("custom-error", "custom-description", "custom-uri");
    given(jwtValidator.validate(any(Jwt.class))).willReturn(OAuth2TokenValidatorResult.failure(error));
    // @formatter:off
    this.mvc.perform(get("/").header("Authorization", "Bearer " + token)).andExpect(status().isUnauthorized()).andExpect(header().string(HttpHeaders.WWW_AUTHENTICATE, containsString("custom-description")));
// @formatter:on
}
Also used : Jwt(org.springframework.security.oauth2.jwt.Jwt) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Test(org.junit.jupiter.api.Test)

Example 9 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class OAuth2ResourceServerBeanDefinitionParserTests method requestWhenJwtAuthenticationConverterThenUsed.

@Test
public void requestWhenJwtAuthenticationConverterThenUsed() throws Exception {
    this.spring.configLocations(xml("MockJwtDecoder"), xml("MockJwtAuthenticationConverter"), xml("JwtAuthenticationConverter")).autowire();
    Converter<Jwt, JwtAuthenticationToken> jwtAuthenticationConverter = (Converter<Jwt, JwtAuthenticationToken>) this.spring.getContext().getBean("jwtAuthenticationConverter");
    given(jwtAuthenticationConverter.convert(any(Jwt.class))).willReturn(new JwtAuthenticationToken(TestJwts.jwt().build(), Collections.emptyList()));
    JwtDecoder jwtDecoder = this.spring.getContext().getBean(JwtDecoder.class);
    given(jwtDecoder.decode(anyString())).willReturn(TestJwts.jwt().build());
    // @formatter:off
    this.mvc.perform(get("/").header("Authorization", "Bearer token")).andExpect(status().isNotFound());
    // @formatter:on
    verify(jwtAuthenticationConverter).convert(any(Jwt.class));
}
Also used : JwtAuthenticationToken(org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken) Jwt(org.springframework.security.oauth2.jwt.Jwt) NimbusJwtDecoder(org.springframework.security.oauth2.jwt.NimbusJwtDecoder) JwtDecoder(org.springframework.security.oauth2.jwt.JwtDecoder) Converter(org.springframework.core.convert.converter.Converter) Test(org.junit.jupiter.api.Test)

Example 10 with JWT

use of com.auth0.jwt.JWT in project spring-security by spring-projects.

the class NimbusJwtClientAuthenticationParametersConverter method convert.

@Override
public MultiValueMap<String, String> convert(T authorizationGrantRequest) {
    Assert.notNull(authorizationGrantRequest, "authorizationGrantRequest cannot be null");
    ClientRegistration clientRegistration = authorizationGrantRequest.getClientRegistration();
    if (!ClientAuthenticationMethod.PRIVATE_KEY_JWT.equals(clientRegistration.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.CLIENT_SECRET_JWT.equals(clientRegistration.getClientAuthenticationMethod())) {
        return null;
    }
    JWK jwk = this.jwkResolver.apply(clientRegistration);
    if (jwk == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_KEY_ERROR_CODE, "Failed to resolve JWK signing key for client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsAlgorithm jwsAlgorithm = resolveAlgorithm(jwk);
    if (jwsAlgorithm == null) {
        OAuth2Error oauth2Error = new OAuth2Error(INVALID_ALGORITHM_ERROR_CODE, "Unable to resolve JWS (signing) algorithm from JWK associated to client registration '" + clientRegistration.getRegistrationId() + "'.", null);
        throw new OAuth2AuthorizationException(oauth2Error);
    }
    JwsHeader.Builder headersBuilder = JwsHeader.with(jwsAlgorithm);
    Instant issuedAt = Instant.now();
    Instant expiresAt = issuedAt.plus(Duration.ofSeconds(60));
    // @formatter:off
    JwtClaimsSet.Builder claimsBuilder = JwtClaimsSet.builder().issuer(clientRegistration.getClientId()).subject(clientRegistration.getClientId()).audience(Collections.singletonList(clientRegistration.getProviderDetails().getTokenUri())).id(UUID.randomUUID().toString()).issuedAt(issuedAt).expiresAt(expiresAt);
    // @formatter:on
    JwsHeader jwsHeader = headersBuilder.build();
    JwtClaimsSet jwtClaimsSet = claimsBuilder.build();
    JwsEncoderHolder jwsEncoderHolder = this.jwsEncoders.compute(clientRegistration.getRegistrationId(), (clientRegistrationId, currentJwsEncoderHolder) -> {
        if (currentJwsEncoderHolder != null && currentJwsEncoderHolder.getJwk().equals(jwk)) {
            return currentJwsEncoderHolder;
        }
        JWKSource<SecurityContext> jwkSource = new ImmutableJWKSet<>(new JWKSet(jwk));
        return new JwsEncoderHolder(new NimbusJwtEncoder(jwkSource), jwk);
    });
    JwtEncoder jwsEncoder = jwsEncoderHolder.getJwsEncoder();
    Jwt jws = jwsEncoder.encode(JwtEncoderParameters.from(jwsHeader, jwtClaimsSet));
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION_TYPE, CLIENT_ASSERTION_TYPE_VALUE);
    parameters.set(OAuth2ParameterNames.CLIENT_ASSERTION, jws.getTokenValue());
    return parameters;
}
Also used : OAuth2AuthorizationException(org.springframework.security.oauth2.core.OAuth2AuthorizationException) JwsAlgorithm(org.springframework.security.oauth2.jose.jws.JwsAlgorithm) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) Jwt(org.springframework.security.oauth2.jwt.Jwt) Instant(java.time.Instant) OAuth2Error(org.springframework.security.oauth2.core.OAuth2Error) JwsHeader(org.springframework.security.oauth2.jwt.JwsHeader) JwtEncoder(org.springframework.security.oauth2.jwt.JwtEncoder) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) JwtClaimsSet(org.springframework.security.oauth2.jwt.JwtClaimsSet) NimbusJwtEncoder(org.springframework.security.oauth2.jwt.NimbusJwtEncoder) ClientRegistration(org.springframework.security.oauth2.client.registration.ClientRegistration) JWKSet(com.nimbusds.jose.jwk.JWKSet) ImmutableJWKSet(com.nimbusds.jose.jwk.source.ImmutableJWKSet) SecurityContext(com.nimbusds.jose.proc.SecurityContext) JWK(com.nimbusds.jose.jwk.JWK)

Aggregations

Jwt (org.springframework.security.oauth2.jwt.Jwt)96 Test (org.junit.jupiter.api.Test)78 GrantedAuthority (org.springframework.security.core.GrantedAuthority)49 SimpleGrantedAuthority (org.springframework.security.core.authority.SimpleGrantedAuthority)39 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)19 ClientRegistration (org.springframework.security.oauth2.client.registration.ClientRegistration)18 TestJwts (org.springframework.security.oauth2.jwt.TestJwts)18 Arrays (java.util.Arrays)17 List (java.util.List)17 DecodedJWT (com.auth0.jwt.interfaces.DecodedJWT)16 AbstractAuthenticationToken (org.springframework.security.authentication.AbstractAuthenticationToken)16 Test (org.junit.Test)14 OAuth2AccessTokenResponse (org.springframework.security.oauth2.core.endpoint.OAuth2AccessTokenResponse)13 Authentication (org.springframework.security.core.Authentication)12 HashMap (java.util.HashMap)11 Assertions.assertThatIllegalArgumentException (org.assertj.core.api.Assertions.assertThatIllegalArgumentException)11 BeforeEach (org.junit.jupiter.api.BeforeEach)11 Map (java.util.Map)10 SecurityContext (org.springframework.security.core.context.SecurityContext)10 JwtAuthenticationToken (org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken)10