org.keycloak.common.util.Base64Url Java Examples

The following examples show how to use org.keycloak.common.util.Base64Url. 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: 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 #2
Source File: RegisterAuthenticator.java    From keycloak-webauthn-authenticator with Apache License 2.0 6 votes vote down vote up
@Override
public void requiredActionChallenge(RequiredActionContext context) {
    String userid = context.getUser().getId();
    String username = context.getUser().getUsername();
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    String origin = context.getUriInfo().getBaseUri().getHost();
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);

    Response form = context.form()
            .setAttribute(WebAuthnConstants.ORIGIN, origin)
            .setAttribute(WebAuthnConstants.CHALLENGE, challengeValue)
            .setAttribute(WebAuthnConstants.USER_ID, userid)
            .setAttribute(WebAuthnConstants.USER_NAME, username)
            .createForm("webauthn-register.ftl");
    context.challenge(form);
}
 
Example #3
Source File: GeneratedHmacKeyProviderTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void updateKeysize() throws Exception {
    long priority = System.currentTimeMillis();

    ComponentRepresentation rep = createRep("valid", GeneratedHmacKeyProviderFactory.ID);
    rep.setConfig(new MultivaluedHashMap<>());
    rep.getConfig().putSingle("priority", Long.toString(priority));

    Response response = adminClient.realm("test").components().add(rep);
    String id = ApiUtil.getCreatedId(response);
    response.close();

    ComponentRepresentation component = testingClient.server("test").fetch(RunHelpers.internalComponent(id));
    assertEquals(64, Base64Url.decode(component.getConfig().getFirst("secret")).length);

    ComponentRepresentation createdRep = adminClient.realm("test").components().component(id).toRepresentation();
    createdRep.getConfig().putSingle("secretSize", "512");
    adminClient.realm("test").components().component(id).update(createdRep);

    component = testingClient.server("test").fetch(RunHelpers.internalComponent(id));
    assertEquals(512, Base64Url.decode(component.getConfig().getFirst("secret")).length);
}
 
Example #4
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 #5
Source File: JWE.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private JWE getProcessedJWE(JWEAlgorithmProvider algorithmProvider, JWEEncryptionProvider encryptionProvider) throws Exception {
    if (algorithmProvider == null) {
        throw new IllegalArgumentException("No provider for alg ");
    }

    if (encryptionProvider == null) {
        throw new IllegalArgumentException("No provider for enc ");
    }

    keyStorage.setEncryptionProvider(encryptionProvider);

    byte[] decodedCek = algorithmProvider.decodeCek(Base64Url.decode(base64Cek), keyStorage.getDecryptionKey());
    keyStorage.setCEKBytes(decodedCek);

    encryptionProvider.verifyAndDecodeJwe(this);

    return this;
}
 
Example #6
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
 
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);
    form.setAttribute(WebAuthnConstants.CHALLENGE, challengeValue);

    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = getRpID(context);
    form.setAttribute(WebAuthnConstants.RP_ID, rpId);

    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already been identified
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators().isEmpty()) {
            // require the user to register webauthn authenticator
            return;
        }
        isUserIdentified = true;
        form.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
    } else {
        // in ID-less & Password-less Scenario
        // NOP
    }
    form.setAttribute(WebAuthnConstants.IS_USER_IDENTIFIED, Boolean.toString(isUserIdentified));

    // read options from policy
    String userVerificationRequirement = policy.getUserVerificationRequirement();
    form.setAttribute(WebAuthnConstants.USER_VERIFICATION, userVerificationRequirement);

    context.challenge(form.createLoginWebAuthn());
}
 
Example #7
Source File: AbstractIdentityProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected String getLinkingUrl(UriInfo uriInfo, ClientModel authorizedClient, UserSessionModel tokenUserSession) {
    String provider = getConfig().getAlias();
    String clientId = authorizedClient.getClientId();
    String nonce = UUID.randomUUID().toString();
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("SHA-256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    String input = nonce + tokenUserSession.getId() + clientId + provider;
    byte[] check = md.digest(input.getBytes(StandardCharsets.UTF_8));
    String hash = Base64Url.encode(check);
    return KeycloakUriBuilder.fromUri(uriInfo.getBaseUri())
            .path("/realms/{realm}/broker/{provider}/link")
            .queryParam("nonce", nonce)
            .queryParam("hash", hash)
            .queryParam("client_id", clientId)
            .build(authorizedClient.getRealm().getName(), provider)
            .toString();
}
 
Example #8
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 #9
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 #10
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 #11
Source File: JWKBuilder.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public JWK rsa(Key key, X509Certificate certificate) {
    RSAPublicKey rsaKey = (RSAPublicKey) key;

    RSAPublicJWK k = new RSAPublicJWK();

    String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key);
    k.setKeyId(kid);
    k.setKeyType(KeyType.RSA);
    k.setAlgorithm(algorithm);
    k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE);
    k.setModulus(Base64Url.encode(toIntegerBytes(rsaKey.getModulus())));
    k.setPublicExponent(Base64Url.encode(toIntegerBytes(rsaKey.getPublicExponent())));
    
    if (certificate != null) {
        k.setX509CertificateChain(new String [] {PemUtils.encodeCertificate(certificate)});
    }

    return k;
}
 
Example #12
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidRequestWithClaimsFromPublicClient() throws IOException {
    oauth.realm("authz-test");
    oauth.clientId(PUBLIC_TEST_CLIENT);

    oauth.doLogin("marta", "password");

    // Token request
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);

    AuthorizationRequest request = new AuthorizationRequest();

    request.addPermission("Resource 13");
    HashMap<Object, Object> obj = new HashMap<>();

    obj.put("claim-a", "claim-a");

    request.setClaimToken(Base64Url.encode(JsonSerialization.writeValueAsBytes(obj)));
    this.expectedException.expect(AuthorizationDeniedException.class);
    this.expectedException.expectCause(Matchers.allOf(Matchers.instanceOf(HttpResponseException.class), Matchers.hasProperty("statusCode", Matchers.is(403))));
    this.expectedException.expectMessage("Public clients are not allowed to send claims");
    this.expectedException.reportMissingExceptionWithMessage("Should fail, public clients not allowed");

    getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(response.getAccessToken()).authorize(request);
}
 
Example #13
Source File: JWKBuilder.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public JWK ec(Key key) {
    ECPublicKey ecKey = (ECPublicKey) key;

    ECPublicJWK k = new ECPublicJWK();

    String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key);
    int fieldSize = ecKey.getParams().getCurve().getField().getFieldSize();
    BigInteger affineX = ecKey.getW().getAffineX();
    BigInteger affineY = ecKey.getW().getAffineY();

    k.setKeyId(kid);
    k.setKeyType(KeyType.EC);
    k.setAlgorithm(algorithm);
    k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE);
    k.setCrv("P-" + fieldSize);
    k.setX(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineX())));
    k.setY(Base64Url.encode(toIntegerBytes(ecKey.getW().getAffineY())));
    
    return k;
}
 
Example #14
Source File: HMACProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verify(JWSInput input, byte[] sharedSecret) {
    try {
        byte[] signature = sign(input.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8), input.getHeader().getAlgorithm(), sharedSecret);
        return MessageDigest.isEqual(signature, Base64Url.decode(input.getEncodedSignature()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #15
Source File: HMACProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean verify(JWSInput input, SecretKey key) {
    try {
        byte[] signature = sign(input.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8), input.getHeader().getAlgorithm(), key);
        return MessageDigest.isEqual(signature, Base64Url.decode(input.getEncodedSignature()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: WelcomeResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String setCsrfCookie() {
    String stateChecker = Base64Url.encode(KeycloakModelUtils.generateSecret());
    String cookiePath = session.getContext().getUri().getPath();
    boolean secureOnly = session.getContext().getUri().getRequestUri().getScheme().equalsIgnoreCase("https");
    CookieHelper.addCookie(KEYCLOAK_STATE_CHECKER, stateChecker, cookiePath, null, null, 300, secureOnly, true);
    return stateChecker;
}
 
Example #17
Source File: SerializedBrokeredIdentityContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@JsonIgnore
@Override
public void setAttribute(String key, List<String> value) {
    try {
        byte[] listBytes = JsonSerialization.writeValueAsBytes(value);
        String listStr = Base64Url.encode(listBytes);
        ContextDataEntry ctxEntry = ContextDataEntry.create(List.class.getName(), listStr);
        this.contextData.put(Constants.USER_ATTRIBUTES_PREFIX + key, ctxEntry);
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}
 
Example #18
Source File: PkceGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String generateS256CodeChallenge(String codeVerifier) {
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(codeVerifier.getBytes("ISO_8859_1"));
        byte[] digestBytes = md.digest();
        String codeChallenge = Base64Url.encode(digestBytes);
        return codeChallenge;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: JWE.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String getEncodedJweString() {
    StringBuilder builder = new StringBuilder();
    builder.append(base64Header).append(".")
            .append(base64Cek).append(".")
            .append(Base64Url.encode(initializationVector)).append(".")
            .append(Base64Url.encode(encryptedContent)).append(".")
            .append(Base64Url.encode(authenticationTag));

    return builder.toString();
}
 
Example #20
Source File: JWSBuilder.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected String encodeAll(StringBuilder encoding, byte[] signature) {
    encoding.append('.');
    if (signature != null) {
        encoding.append(Base64Url.encode(signature));
    }
    return encoding.toString();
}
 
Example #21
Source File: CodeGenerateUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public String retrieveCode(KeycloakSession session, AuthenticationSessionModel authSession) {
    String nextCode = authSession.getAuthNote(ACTIVE_CODE);
    if (nextCode == null) {
        String actionId = Base64Url.encode(KeycloakModelUtils.generateSecret());
        authSession.setAuthNote(ACTIVE_CODE, actionId);
        nextCode = actionId;
    } else {
        logger.debug("Code already generated for authentication session, using same code");
    }

    return nextCode;
}
 
Example #22
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static IdentityCookieToken createIdentityToken(KeycloakSession keycloakSession, RealmModel realm, UserModel user, UserSessionModel session, String issuer) {
    IdentityCookieToken token = new IdentityCookieToken();
    token.id(KeycloakModelUtils.generateId());
    token.issuedNow();
    token.subject(user.getId());
    token.issuer(issuer);
    token.type(TokenUtil.TOKEN_TYPE_KEYCLOAK_ID);

    if (session != null) {
        token.setSessionState(session.getId());
    }

    if (session != null && session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespanRememberMe());
    } else if (realm.getSsoSessionMaxLifespan() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespan());
    }

    String stateChecker = (String) keycloakSession.getAttribute("state_checker");
    if (stateChecker == null) {
        stateChecker = Base64Url.encode(KeycloakModelUtils.generateSecret());
        keycloakSession.setAttribute("state_checker", stateChecker);
    }
    token.getOtherClaims().put("state_checker", stateChecker);

    return token;
}
 
Example #23
Source File: MtlsHoKTokenUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private static String getCertificateThumbprintInSHA256DERX509Base64UrlEncoded (X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException {
    // need to calculate over DER encoding of the X.509 certificate
    //   https://tools.ietf.org/html/draft-ietf-oauth-mtls-08#section-3.1
    // in order to do that, call getEncoded()
    //   https://docs.oracle.com/javase/8/docs/api/java/security/cert/Certificate.html#getEncoded--
    byte[] DERX509Hash = cert.getEncoded();
    MessageDigest md = MessageDigest.getInstance(DIGEST_ALG);
    md.update(DERX509Hash);
    String DERX509Base64UrlEncoded = Base64Url.encode(md.digest());
    return DERX509Base64UrlEncoded;
}
 
Example #24
Source File: OIDCIdentityProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected UriBuilder createAuthorizationUrl(AuthenticationRequest request) {
    UriBuilder uriBuilder = super.createAuthorizationUrl(request);
    String nonce = Base64Url.encode(KeycloakModelUtils.generateSecret(16));
    AuthenticationSessionModel authenticationSession = request.getAuthenticationSession();

    authenticationSession.setClientNote(BROKER_NONCE_PARAM, nonce);
    uriBuilder.queryParam(OIDCLoginProtocol.NONCE_PARAM, nonce);
    
    return uriBuilder;
}
 
Example #25
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 #26
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 #27
Source File: AbstractGeneratedSecretKeyProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AbstractGeneratedSecretKeyProvider(ComponentModel model, KeyUse use, String type, String algorithm) {
    this.status = KeyStatus.from(model.get(Attributes.ACTIVE_KEY, true), model.get(Attributes.ENABLED_KEY, true));
    this.kid = model.get(Attributes.KID_KEY);
    this.model = model;
    this.use = use;
    this.type = type;
    this.algorithm = algorithm;

    if (model.hasNote(SecretKey.class.getName())) {
        secretKey = model.getNote(SecretKey.class.getName());
    } else {
        secretKey = KeyUtils.loadSecretKey(Base64Url.decode(model.get(Attributes.SECRET_KEY)), JavaAlgorithm.getJavaAlgorithm(algorithm));
        model.setNote(SecretKey.class.getName(), secretKey);
    }
}
 
Example #28
Source File: AbstractGeneratedSecretKeyProviderFactory.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void generateSecret(ComponentModel model, int size) {
    try {
        byte[] secret = KeycloakModelUtils.generateSecret(size);
        model.put(Attributes.SECRET_KEY, Base64Url.encode(secret));

        String kid = KeycloakModelUtils.generateId();
        model.put(Attributes.KID_KEY, kid);
    } catch (Throwable t) {
        throw new ComponentValidationException("Failed to generate secret", t);
    }
}
 
Example #29
Source File: KeycloakSecurityContext.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private <T> T parseToken(String encoded, Class<T> clazz) throws IOException {
    if (encoded == null)
        return null;

    String[] parts = encoded.split("\\.");
    if (parts.length < 2 || parts.length > 3) throw new IllegalArgumentException("Parsing error");

    byte[] bytes = Base64Url.decode(parts[1]);
    return JsonSerialization.readValue(bytes, clazz);
}
 
Example #30
Source File: QuarkusWelcomeResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private String setCsrfCookie() {
    String stateChecker = Base64Url.encode(KeycloakModelUtils.generateSecret());
    String cookiePath = session.getContext().getUri().getPath();
    boolean secureOnly = session.getContext().getUri().getRequestUri().getScheme().equalsIgnoreCase("https");
    CookieHelper.addCookie(KEYCLOAK_STATE_CHECKER, stateChecker, cookiePath, null, null, 300, secureOnly, true);
    return stateChecker;
}