Java Code Examples for org.keycloak.common.util.Base64Url#decode()

The following examples show how to use org.keycloak.common.util.Base64Url#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebAuthnCredentialProviderTest.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
private WebAuthnAuthenticationContext getValidWebAuthnAuthenticationContext(String base64UrlCredentialId) {
    // mimic valid or invalid model created on Authentication
    byte[] credentialId = Base64Url.decode(base64UrlCredentialId);
    byte[] clientDataJSON = Base64Url.decode("eyJjaGFsbGVuZ2UiOiJ0R3o3R3RUQVE2T3FwVHpoOEtLQnFRIiwib3JpZ2luIjoiaHR0cDovL2xvY2FsaG9zdDo4MDgwIiwidHlwZSI6IndlYmF1dGhuLmdldCJ9");
    byte[] authenticatorData = Base64Url.decode("SZYN5YgOjGh0NBcPZHZgW4_krrmihjLHmVzzuoMdl2MBAAAAdg");
    byte[] signature = Base64Url.decode("MEUCIEaZhQ5dXi_C3IxU68ujLLt0DEcyk2EFPz_y45wYUA7AAiEAwkX86OFwpNzPRjSljTaTJVvZ_x9E6xnKhSmsKkUgmlo");
    Origin origin = new Origin("http://localhost:8080");
    Challenge challenge = new DefaultChallenge("tGz7GtTAQ6OqpTzh8KKBqQ");
    ServerProperty server = new ServerProperty(origin, "localhost", challenge, null);
    WebAuthnAuthenticationContext authenticationContext = new WebAuthnAuthenticationContext(
            credentialId,
            clientDataJSON,
            authenticatorData,
            signature,
            server,
            false
    );
    return authenticationContext;
}
 
Example 2
Source File: JWSInput.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public JWSInput(String wire) throws JWSInputException {
    try {
        this.wireString = wire;
        String[] parts = wire.split("\\.");
        if (parts.length < 2 || parts.length > 3) throw new IllegalArgumentException("Parsing error");
        encodedHeader = parts[0];
        encodedContent = parts[1];
        encodedSignatureInput = encodedHeader + '.' + encodedContent;
        content = Base64Url.decode(encodedContent);
        if (parts.length > 2) {
            encodedSignature = parts[2];
            signature = Base64Url.decode(encodedSignature);

        }
        byte[] headerBytes = Base64Url.decode(encodedHeader);
        header = JsonSerialization.readValue(headerBytes, JWSHeader.class);
    } catch (Throwable t) {
        throw new JWSInputException(t);
    }
}
 
Example 3
Source File: AbstractGeneratedSecretKeyProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {
    ConfigurationValidationHelper validation = SecretKeyProviderUtils.validateConfiguration(model);
    validation.checkList(Attributes.SECRET_SIZE_PROPERTY, false);

    int size = model.get(Attributes.SECRET_SIZE_KEY, getDefaultKeySize());

    if (!(model.contains(Attributes.SECRET_KEY))) {
        generateSecret(model, size);
        logger().debugv("Generated secret for {0}", realm.getName());
    } else {
        int currentSize = Base64Url.decode(model.get(Attributes.SECRET_KEY)).length;
        if (currentSize != size) {
            generateSecret(model, size);
            logger().debugv("Secret size changed, generating new secret for {0}", realm.getName());
        }
    }
}
 
Example 4
Source File: SerializedBrokeredIdentityContext.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@JsonIgnore
@Override
public List<String> getAttribute(String key) {
    ContextDataEntry ctxEntry = this.contextData.get(Constants.USER_ATTRIBUTES_PREFIX + key);
    if (ctxEntry != null) {
        try {
            String asString = ctxEntry.getData();
            byte[] asBytes = Base64Url.decode(asString);
            List<String> asList = JsonSerialization.readValue(asBytes, List.class);
            return asList;
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    } else {
        return null;
    }
}
 
Example 5
Source File: DefaultDataMarshaller.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T deserialize(String serialized, Class<T> clazz) {
    try {
        if (clazz.equals(String.class)) {
            return clazz.cast(serialized);
        } else {
            byte[] bytes = Base64Url.decode(serialized);
            if (List.class.isAssignableFrom(clazz)) {
                List list = JsonSerialization.readValue(bytes, List.class);
                return clazz.cast(list);
            } else {
                return JsonSerialization.readValue(bytes, clazz);
            }
        }
    }  catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example 6
Source File: AccessTokenTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void validateTokenSignatureLength(int expectedLength) {
    oauth.doLogin("test-user@localhost", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");

    String token = response.getAccessToken();
    oauth.verifyToken(token);

    String encodedSignature = token.split("\\.",3)[2];
    byte[] signature = Base64Url.decode(encodedSignature);
    Assert.assertEquals(expectedLength, signature.length);
    oauth.openLogout();
}
 
Example 7
Source File: JWKParser.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private PublicKey createECPublicKey() {
    String crv = (String) jwk.getOtherClaims().get(ECPublicJWK.CRV);
    BigInteger x = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.X)));
    BigInteger y = new BigInteger(1, Base64Url.decode((String) jwk.getOtherClaims().get(ECPublicJWK.Y)));

    String name;
    switch (crv) {
        case "P-256" :
            name = "secp256r1";
            break;
        case "P-384" :
            name = "secp384r1";
            break;
        case "P-521" :
            name = "secp521r1";
            break;
        default :
            throw new RuntimeException("Unsupported curve");
    }

    try {
        ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(name);
        ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
        ECPoint point = new ECPoint(x, y);
        ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);

        KeyFactory kf = KeyFactory.getInstance("ECDSA");
        return kf.generatePublic(pubKeySpec);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: JWKParser.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private PublicKey createRSAPublicKey() {
    BigInteger modulus = new BigInteger(1, Base64Url.decode(jwk.getOtherClaims().get(RSAPublicJWK.MODULUS).toString()));
    BigInteger publicExponent = new BigInteger(1, Base64Url.decode(jwk.getOtherClaims().get(RSAPublicJWK.PUBLIC_EXPONENT).toString()));

    try {
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(new RSAPublicKeySpec(modulus, publicExponent));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: JWE.java    From keycloak with Apache License 2.0 5 votes vote down vote up
JWEHeader getHeader() {
    if (header == null && base64Header != null) {
        try {
            byte[] decodedHeader = Base64Url.decode(base64Header);
            header = JsonSerialization.readValue(decodedHeader, JWEHeader.class);
        } catch (IOException ioe) {
            throw new RuntimeException(ioe);
        }
    }
    return header;
}
 
Example 10
Source File: JWE.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void setupJWEHeader(String jweStr) throws IllegalStateException {
    String[] parts = jweStr.split("\\.");
    if (parts.length != 5) {
        throw new IllegalStateException("Not a JWE String");
    }

    this.base64Header = parts[0];
    this.base64Cek = parts[1];
    this.initializationVector = Base64Url.decode(parts[2]);
    this.encryptedContent = Base64Url.decode(parts[3]);
    this.authenticationTag = Base64Url.decode(parts[4]);

    this.header = getHeader();
}
 
Example 11
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2EncryptedAssertion() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);

    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));

    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);

    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_ENCRYPTED_TARGET, "client-exchanger", "secret", params);

        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");

        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());

        // Decrypt assertion
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, privateKeyFromString(ENCRYPTION_PRIVATE_KEY));
        Assert.assertFalse(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);

        // Expires
        Assert.assertEquals(30, response.getExpiresIn());

        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_ENCRYPTED_TARGET, aud.getAudience().get(0).toString());

        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());

        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
}
 
Example 12
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2SignedAndEncryptedAssertion() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);

    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));

    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);

    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_AND_ENCRYPTED_TARGET, "client-exchanger", "secret", params);

        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");

        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());

        // Verify assertion
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, privateKeyFromString(ENCRYPTION_PRIVATE_KEY));
        Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);
        Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString(REALM_PUBLIC_KEY)));

        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_SIGNED_AND_ENCRYPTED_TARGET, aud.getAudience().get(0).toString());

        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());

        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
}
 
Example 13
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2UnsignedAndUnencryptedAssertion() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);

    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));

    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);

    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_UNSIGNED_AND_UNENCRYPTED_TARGET, "client-exchanger", "secret", params);

        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");

        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());

        // Verify assertion
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Assert.assertFalse(AssertionUtil.isSignedElement(assertionDoc.getDocumentElement()));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionDoc);

        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_UNSIGNED_AND_UNENCRYPTED_TARGET, aud.getAudience().get(0).toString());

        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());

        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
}
 
Example 14
Source File: ClientTokenExchangeSAML2Test.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
@UncaughtServerErrorExpected
public void testImpersonation() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);

    oauth.realm(TEST);
    oauth.clientId("client-exchanger");

    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));

    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);

    // client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client
    {
        params.put(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user");
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "client-exchanger", "secret", params);

        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");

        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());

        // Verify assertion
        Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement();
        Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);
        Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString(REALM_PUBLIC_KEY)));

        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString());

        // NameID
        Assert.assertEquals("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());

        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
}
 
Example 15
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

    context.getEvent().detail(Details.CREDENTIAL_TYPE, getCredentialType());

    // receive error from navigator.credentials.get()
    String errorMsgFromWebAuthnApi = params.getFirst(WebAuthnConstants.ERROR);
    if (errorMsgFromWebAuthnApi != null && !errorMsgFromWebAuthnApi.isEmpty()) {
        setErrorResponse(context, WEBAUTHN_ERROR_API_GET, errorMsgFromWebAuthnApi);
        return;
    }

    String baseUrl = UriUtils.getOrigin(context.getUriInfo().getBaseUri());
    String rpId = getRpID(context);

    Origin origin = new Origin(baseUrl);
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty server = new ServerProperty(origin, rpId, challenge, null);

    byte[] credentialId = Base64Url.decode(params.getFirst(WebAuthnConstants.CREDENTIAL_ID));
    byte[] clientDataJSON = Base64Url.decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] authenticatorData = Base64Url.decode(params.getFirst(WebAuthnConstants.AUTHENTICATOR_DATA));
    byte[] signature = Base64Url.decode(params.getFirst(WebAuthnConstants.SIGNATURE));

    final String userHandle = params.getFirst(WebAuthnConstants.USER_HANDLE);
    final String userId;
    // existing User Handle means that the authenticator used Resident Key supported public key credential
    if (userHandle == null || userHandle.isEmpty()) {
        // Resident Key not supported public key credential was used
        // so rely on the user that has already been authenticated
        userId = context.getUser().getId();
    } else {
        // decode using the same charset as it has been encoded (see: WebAuthnRegister.java)
        userId = new String(Base64Url.decode(userHandle), StandardCharsets.UTF_8);
        if (context.getUser() != null) {
            // Resident Key supported public key credential was used,
            // so need to confirm whether the already authenticated user is equals to one authenticated by the webauthn authenticator
            String firstAuthenticatedUserId = context.getUser().getId();
            if (firstAuthenticatedUserId != null && !firstAuthenticatedUserId.equals(userId)) {
                context.getEvent()
                        .detail("first_authenticated_user_id", firstAuthenticatedUserId)
                        .detail("web_authn_authenticator_authenticated_user_id", userId);
                setErrorResponse(context, WEBAUTHN_ERROR_DIFFERENT_USER, null);
                return;
            }
        } else {
            // Resident Key supported public key credential was used,
            // and the user has not yet been identified
            // so rely on the user authenticated by the webauthn authenticator
            // NOP
        }
    }

    boolean isUVFlagChecked = false;
    String userVerificationRequirement = getWebAuthnPolicy(context).getUserVerificationRequirement();
    if (WebAuthnConstants.OPTION_REQUIRED.equals(userVerificationRequirement)) isUVFlagChecked = true;

    UserModel user = session.users().getUserById(userId, context.getRealm());

    AuthenticationRequest authenticationRequest = new AuthenticationRequest(
            credentialId,
            authenticatorData,
            clientDataJSON,
            signature
            );

    AuthenticationParameters authenticationParameters = new AuthenticationParameters(
            server,
            null, // here authenticator cannot be fetched, set it afterwards in WebAuthnCredentialProvider.isValid()
            isUVFlagChecked
            );

    WebAuthnCredentialModelInput cred = new WebAuthnCredentialModelInput(getCredentialType());

    cred.setAuthenticationRequest(authenticationRequest);
    cred.setAuthenticationParameters(authenticationParameters);

    boolean result = false;
    try {
        result = session.userCredentialManager().isValid(context.getRealm(), user, cred);
    } catch (WebAuthnException wae) {
        setErrorResponse(context, WEBAUTHN_ERROR_AUTH_VERIFICATION, wae.getMessage());
        return;
    }
    String encodedCredentialID = Base64Url.encode(credentialId);
    if (result) {
        String isUVChecked = Boolean.toString(isUVFlagChecked);
        logger.debugv("WebAuthn Authentication successed. isUserVerificationChecked = {0}, PublicKeyCredentialID = {1}", isUVChecked, encodedCredentialID);
        context.setUser(user);
        context.getEvent()
            .detail("web_authn_authenticator_user_verification_checked", isUVChecked)
            .detail("public_key_credential_id", encodedCredentialID);
        context.success();
    } else {
        context.getEvent()
            .detail("web_authn_authenticated_user_id", userId)
            .detail("public_key_credential_id", encodedCredentialID);
        setErrorResponse(context, WEBAUTHN_ERROR_USER_NOT_FOUND, null);
        context.cancelLogin();
    }
}
 
Example 16
Source File: AttestationStatementConverter.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public AttestationStatement convertToEntityAttribute(String dbData) {
    byte[] data = Base64Url.decode(dbData);
    AttestationStatementSerializationContainer container = cborConverter.readValue(data, AttestationStatementSerializationContainer.class);
    return container.getAttestationStatement();
}
 
Example 17
Source File: CarsAppController.java    From devconf2019-authz with Apache License 2.0 4 votes vote down vote up
@RequestMapping(value = "/app/img/{carId}", method = RequestMethod.GET)
@ResponseBody
public void getCarImg(Principal principal, Model model, @PathVariable String carId) throws IOException {
    CarsClientService.ClientCallResponse<CarRepresentation> clientResponse = carsClientService.getCarWithDetails(carId);

    String reqSubmitted = handleRequestSubmitted(clientResponse, principal, model);
    // Shoudln't happen
    if (reqSubmitted != null) return;



    CarRepresentation detailedCar = clientResponse.getResult();
    String imgString = detailedCar.getBase64Img();

    response.setContentType("image/jpeg");
    ServletOutputStream outputStream = response.getOutputStream();

    byte[] decodedPicture = Base64Url.decode(imgString);
    outputStream.write(decodedPicture);

    outputStream.flush();
}
 
Example 18
Source File: JWETest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void externalJweAes128KeyWrapTest() throws Exception {
    // See example "A.3" from JWE specification - https://tools.ietf.org/html/rfc7516#page-41
    String externalJwe = "eyJhbGciOiJBMTI4S1ciLCJlbmMiOiJBMTI4Q0JDLUhTMjU2In0.6KB707dM9YTIgHtLvtgWQ8mKwboJW3of9locizkDTHzBC2IlrT1oOQ.AxY8DCtDaGlsbGljb3RoZQ.KDlTtXchhZTGufMYmOYGS4HffxPSUrfmqCHXaI9wOGY.U0m_YmjN04DJvceFICbCVQ";

    byte[] aesKey = Base64Url.decode("GawgguFyGrWKav7AX4VKUg");
    SecretKeySpec aesKeySpec = new SecretKeySpec(aesKey, "AES");

    JWE jwe = new JWE();
    jwe.getKeyStorage()
            .setDecryptionKey(aesKeySpec);

    jwe.verifyAndDecodeJwe(externalJwe);

    String decodedContent = new String(jwe.getContent(), StandardCharsets.UTF_8);

    Assert.assertEquals("Live long and prosper.", decodedContent);

}
 
Example 19
Source File: WebAuthn4jAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 4 votes vote down vote up
public void action(AuthenticationFlowContext context) {
    MultivaluedMap<String, String> params = context.getHttpRequest().getDecodedFormParameters();

    // receive error from navigator.credentials.get()
    String error = params.getFirst(WebAuthnConstants.ERROR);
    if (error != null && !error.isEmpty()) {
        throw new AuthenticationFlowException("exception raised from navigator.credentials.get() : " + error, AuthenticationFlowError.INVALID_USER);
    }

    String baseUrl = UriUtils.getOrigin(context.getUriInfo().getBaseUri());
    String rpId = context.getUriInfo().getBaseUri().getHost();

    Origin origin = new Origin(baseUrl);
    Challenge challenge = new DefaultChallenge(context.getAuthenticationSession().getAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE));
    ServerProperty server = new ServerProperty(origin, rpId, challenge, null);

    byte[] credentialId = Base64Url.decode(params.getFirst(WebAuthnConstants.CREDENTIAL_ID));
    byte[] clientDataJSON = Base64Url.decode(params.getFirst(WebAuthnConstants.CLIENT_DATA_JSON));
    byte[] authenticatorData = Base64Url.decode(params.getFirst(WebAuthnConstants.AUTHENTICATOR_DATA));
    byte[] signature = Base64Url.decode(params.getFirst(WebAuthnConstants.SIGNATURE));

    String userId = params.getFirst(WebAuthnConstants.USER_HANDLE);
    boolean isUVFlagChecked = true;
    logger.debugv("userId = {0}", userId);

    if (userId == null || userId.isEmpty()) {
        // in 2 Factor with Resident Key not supported Authenticator Scenario
        userId = context.getUser().getId();
        isUVFlagChecked = false;
    } else {
        if (context.getUser() != null) {
            // in 2 Factor with Resident Key supported Authenticator Scenario
            String firstAuthenticatedUserId = context.getUser().getId();
            logger.debugv("firstAuthenticatedUserId = {0}", firstAuthenticatedUserId);
            if (firstAuthenticatedUserId != null && !firstAuthenticatedUserId.equals(userId)) {
                throw new AuthenticationFlowException("First authenticated user is not the one authenticated by 2nd factor authenticator", AuthenticationFlowError.USER_CONFLICT);
            }
        } else {
            // in Passwordless with Resident Key supported Authenticator Scenario
            // NOP
        }
    }
    UserModel user = session.users().getUserById(userId, context.getRealm());
    WebAuthnAuthenticationContext authenticationContext = new WebAuthnAuthenticationContext(
            credentialId,
            clientDataJSON,
            authenticatorData,
            signature,
            server,
            isUVFlagChecked
    );

    WebAuthnCredentialModel cred = new WebAuthnCredentialModel();
    cred.setAuthenticationContext(authenticationContext);

    boolean result = false;
    try {
        result = session.userCredentialManager().isValid(context.getRealm(), user, cred);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationFlowException("unknown user authenticated by the authenticator", AuthenticationFlowError.UNKNOWN_USER);
    }
    if (result) {
        context.setUser(user);
        context.success();
    } else {
        context.cancelLogin();
    }
}
 
Example 20
Source File: JWKTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void publicEs256() throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
    SecureRandom randomGen = SecureRandom.getInstance("SHA1PRNG");
    ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256r1");
    keyGen.initialize(ecSpec, randomGen);
    KeyPair keyPair = keyGen.generateKeyPair();

    PublicKey publicKey = keyPair.getPublic();

    JWK jwk = JWKBuilder.create().kid(KeyUtils.createKeyId(keyPair.getPublic())).algorithm("ES256").ec(publicKey);

    assertEquals("EC", jwk.getKeyType());
    assertEquals("ES256", jwk.getAlgorithm());
    assertEquals("sig", jwk.getPublicKeyUse());

    assertTrue(jwk instanceof ECPublicJWK);

    ECPublicJWK ecJwk = (ECPublicJWK) jwk;

    assertNotNull(ecJwk.getCrv());
    assertNotNull(ecJwk.getX());
    assertNotNull(ecJwk.getY());

    byte[] xBytes = Base64Url.decode(ecJwk.getX());
    byte[] yBytes = Base64Url.decode(ecJwk.getY());

    assertEquals(256/8, xBytes.length);
    assertEquals(256/8, yBytes.length);

    String jwkJson = JsonSerialization.writeValueAsString(jwk);

    JWKParser parser = JWKParser.create().parse(jwkJson);
    PublicKey publicKeyFromJwk = parser.toPublicKey();

    assertArrayEquals(publicKey.getEncoded(), publicKeyFromJwk.getEncoded());

    byte[] data = "Some test string".getBytes(StandardCharsets.UTF_8);
    byte[] sign = sign(data, JavaAlgorithm.ES256, keyPair.getPrivate());
    verify(data, sign, JavaAlgorithm.ES256, publicKeyFromJwk);
}