Search in sources :

Example 91 with MediaType

use of javax.ws.rs.core.MediaType in project entando-core by entando.

the class TestApiI18nLabelInterface method testCreateNewContentFromJson.

public void testCreateNewContentFromJson() throws Throwable {
    MediaType mediaType = MediaType.APPLICATION_JSON_TYPE;
    this.testCreateNewLabel(mediaType);
}
Also used : MediaType(javax.ws.rs.core.MediaType)

Example 92 with MediaType

use of javax.ws.rs.core.MediaType in project entando-core by entando.

the class TestApiI18nLabelInterface method testCreateNewLabelFromXml.

public void testCreateNewLabelFromXml() throws Throwable {
    MediaType mediaType = MediaType.APPLICATION_XML_TYPE;
    this.testCreateNewLabel(mediaType);
}
Also used : MediaType(javax.ws.rs.core.MediaType)

Example 93 with MediaType

use of javax.ws.rs.core.MediaType in project iaf by ibissource.

the class TransactionalStorage method downloadPipeMessage.

@GET
@RolesAllowed({ "IbisDataAdmin", "IbisAdmin", "IbisTester" })
@Path("/adapters/{adapterName}/pipes/{pipeName}/messages/{messageId}/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadPipeMessage(@PathParam("adapterName") String adapterName, @PathParam("pipeName") String pipeName, @PathParam("messageId") String messageId) throws ApiException {
    Adapter adapter = getIbisManager().getRegisteredAdapter(adapterName);
    if (adapter == null) {
        throw new ApiException("Adapter not found!");
    }
    MessageSendingPipe pipe = (MessageSendingPipe) adapter.getPipeLine().getPipe(pipeName);
    if (pipe == null) {
        throw new ApiException("Pipe [" + pipeName + "] not found!");
    }
    // messageId is double URLEncoded, because it can contain '/' in ExchangeMailListener
    messageId = Misc.urlDecode(messageId);
    String message = getMessage(pipe.getMessageLog(), messageId);
    MediaType mediaType = getMediaType(message);
    String contentDispositionHeader = getContentDispositionHeader(mediaType, messageId);
    return Response.status(Response.Status.OK).type(mediaType).entity(message).header("Content-Disposition", contentDispositionHeader).build();
}
Also used : MessageSendingPipe(nl.nn.adapterframework.pipes.MessageSendingPipe) MediaType(javax.ws.rs.core.MediaType) Adapter(nl.nn.adapterframework.core.Adapter) Path(javax.ws.rs.Path) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 94 with MediaType

use of javax.ws.rs.core.MediaType in project keycloak by keycloak.

the class OIDCIdentityProvider method extractIdentity.

protected BrokeredIdentityContext extractIdentity(AccessTokenResponse tokenResponse, String accessToken, JsonWebToken idToken) throws IOException {
    String id = idToken.getSubject();
    BrokeredIdentityContext identity = new BrokeredIdentityContext(id);
    String name = (String) idToken.getOtherClaims().get(IDToken.NAME);
    String givenName = (String) idToken.getOtherClaims().get(IDToken.GIVEN_NAME);
    String familyName = (String) idToken.getOtherClaims().get(IDToken.FAMILY_NAME);
    String preferredUsername = (String) idToken.getOtherClaims().get(getusernameClaimNameForIdToken());
    String email = (String) idToken.getOtherClaims().get(IDToken.EMAIL);
    if (!getConfig().isDisableUserInfoService()) {
        String userInfoUrl = getUserInfoUrl();
        if (userInfoUrl != null && !userInfoUrl.isEmpty()) {
            if (accessToken != null) {
                SimpleHttp.Response response = executeRequest(userInfoUrl, SimpleHttp.doGet(userInfoUrl, session).header("Authorization", "Bearer " + accessToken));
                String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE);
                MediaType contentMediaType;
                try {
                    contentMediaType = MediaType.valueOf(contentType);
                } catch (IllegalArgumentException ex) {
                    contentMediaType = null;
                }
                if (contentMediaType == null || contentMediaType.isWildcardSubtype() || contentMediaType.isWildcardType()) {
                    throw new RuntimeException("Unsupported content-type [" + contentType + "] in response from [" + userInfoUrl + "].");
                }
                JsonNode userInfo;
                if (MediaType.APPLICATION_JSON_TYPE.isCompatible(contentMediaType)) {
                    userInfo = response.asJson();
                } else if (APPLICATION_JWT_TYPE.isCompatible(contentMediaType)) {
                    JWSInput jwsInput;
                    try {
                        jwsInput = new JWSInput(response.asString());
                    } catch (JWSInputException cause) {
                        throw new RuntimeException("Failed to parse JWT userinfo response", cause);
                    }
                    if (verify(jwsInput)) {
                        userInfo = JsonSerialization.readValue(jwsInput.getContent(), JsonNode.class);
                    } else {
                        throw new RuntimeException("Failed to verify signature of userinfo response from [" + userInfoUrl + "].");
                    }
                } else {
                    throw new RuntimeException("Unsupported content-type [" + contentType + "] in response from [" + userInfoUrl + "].");
                }
                id = getJsonProperty(userInfo, "sub");
                name = getJsonProperty(userInfo, "name");
                givenName = getJsonProperty(userInfo, IDToken.GIVEN_NAME);
                familyName = getJsonProperty(userInfo, IDToken.FAMILY_NAME);
                preferredUsername = getUsernameFromUserInfo(userInfo);
                email = getJsonProperty(userInfo, "email");
                AbstractJsonUserAttributeMapper.storeUserProfileForMapper(identity, userInfo, getConfig().getAlias());
            }
        }
    }
    identity.getContextData().put(VALIDATED_ID_TOKEN, idToken);
    identity.setId(id);
    if (givenName != null) {
        identity.setFirstName(givenName);
    }
    if (familyName != null) {
        identity.setLastName(familyName);
    }
    if (givenName == null && familyName == null) {
        identity.setName(name);
    }
    identity.setEmail(email);
    identity.setBrokerUserId(getConfig().getAlias() + "." + id);
    if (preferredUsername == null) {
        preferredUsername = email;
    }
    if (preferredUsername == null) {
        preferredUsername = id;
    }
    identity.setUsername(preferredUsername);
    if (tokenResponse != null && tokenResponse.getSessionState() != null) {
        identity.setBrokerSessionId(getConfig().getAlias() + "." + tokenResponse.getSessionState());
    }
    if (tokenResponse != null)
        identity.getContextData().put(FEDERATED_ACCESS_TOKEN_RESPONSE, tokenResponse);
    if (tokenResponse != null)
        processAccessTokenResponse(identity, tokenResponse);
    return identity;
}
Also used : SimpleHttp(org.keycloak.broker.provider.util.SimpleHttp) MediaType(javax.ws.rs.core.MediaType) JWSInputException(org.keycloak.jose.jws.JWSInputException) JsonNode(com.fasterxml.jackson.databind.JsonNode) JWSInput(org.keycloak.jose.jws.JWSInput) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext)

Example 95 with MediaType

use of javax.ws.rs.core.MediaType in project keycloak by keycloak.

the class X509ClientAuthenticator method authenticateClient.

@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    X509ClientCertificateLookup provider = context.getSession().getProvider(X509ClientCertificateLookup.class);
    if (provider == null) {
        logger.errorv("\"{0}\" Spi is not available, did you forget to update the configuration?", X509ClientCertificateLookup.class);
        return;
    }
    X509Certificate[] certs = null;
    ClientModel client = null;
    try {
        certs = provider.getCertificateChain(context.getHttpRequest());
        String client_id = null;
        MediaType mediaType = context.getHttpRequest().getHttpHeaders().getMediaType();
        boolean hasFormData = mediaType != null && mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE);
        MultivaluedMap<String, String> formData = hasFormData ? context.getHttpRequest().getDecodedFormParameters() : null;
        MultivaluedMap<String, String> queryParams = context.getSession().getContext().getUri().getQueryParameters();
        if (formData != null) {
            client_id = formData.getFirst(OAuth2Constants.CLIENT_ID);
        }
        if (client_id == null && queryParams != null) {
            client_id = queryParams.getFirst(OAuth2Constants.CLIENT_ID);
        }
        if (client_id == null) {
            client_id = context.getSession().getAttribute("client_id", String.class);
        }
        if (client_id == null) {
            Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_client", "Missing client_id parameter");
            context.challenge(challengeResponse);
            return;
        }
        client = context.getRealm().getClientByClientId(client_id);
        if (client == null) {
            context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
            return;
        }
        context.getEvent().client(client_id);
        context.setClient(client);
        if (!client.isEnabled()) {
            context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
            return;
        }
    } catch (GeneralSecurityException e) {
        logger.errorf("[X509ClientCertificateAuthenticator:authenticate] Exception: %s", e.getMessage());
        context.attempted();
        return;
    }
    if (certs == null || certs.length == 0) {
        // No x509 client cert, fall through and
        // continue processing the rest of the authentication flow
        logger.debug("[X509ClientCertificateAuthenticator:authenticate] x509 client certificate is not available for mutual SSL.");
        context.attempted();
        return;
    }
    OIDCAdvancedConfigWrapper clientCfg = OIDCAdvancedConfigWrapper.fromClientModel(client);
    String subjectDNRegexp = client.getAttribute(ATTR_SUBJECT_DN);
    if (subjectDNRegexp == null || subjectDNRegexp.length() == 0) {
        logger.errorf("[X509ClientCertificateAuthenticator:authenticate] " + ATTR_SUBJECT_DN + " is null or empty");
        context.attempted();
        return;
    }
    Optional<String> matchedCertificate;
    if (clientCfg.getAllowRegexPatternComparison()) {
        Pattern subjectDNPattern = Pattern.compile(subjectDNRegexp);
        matchedCertificate = Arrays.stream(certs).map(certificate -> certificate.getSubjectDN().getName()).filter(subjectdn -> subjectDNPattern.matcher(subjectdn).matches()).findFirst();
    } else {
        // OIDC/OAuth2 does not use regex comparison as it expects exact DN given in the format according to RFC4514. See RFC8705 for the details.
        // We allow custom OIDs attributes to be "expanded" or not expanded in the given Subject DN
        X500Principal expectedDNPrincipal = new X500Principal(subjectDNRegexp, CUSTOM_OIDS_REVERSED);
        matchedCertificate = Arrays.stream(certs).filter(certificate -> expectedDNPrincipal.getName(X500Principal.RFC2253, CUSTOM_OIDS).equals(certificate.getSubjectX500Principal().getName(X500Principal.RFC2253, CUSTOM_OIDS))).map(certificate -> certificate.getSubjectDN().getName()).findFirst();
    }
    if (!matchedCertificate.isPresent()) {
        // We do quite expensive operation here, so better check the logging level beforehand.
        if (logger.isDebugEnabled()) {
            logger.debug("[X509ClientCertificateAuthenticator:authenticate] Couldn't match any certificate for expected Subject DN '" + subjectDNRegexp + "' with allow regex pattern '" + clientCfg.getAllowRegexPatternComparison() + "'.");
            logger.debug("[X509ClientCertificateAuthenticator:authenticate] Available SubjectDNs: " + Arrays.stream(certs).map(cert -> cert.getSubjectDN().getName()).collect(Collectors.toList()));
        }
        context.attempted();
        return;
    } else {
        logger.debug("[X509ClientCertificateAuthenticator:authenticate] Matched " + matchedCertificate.get() + " certificate.");
    }
    context.success();
}
Also used : ClientModel(org.keycloak.models.ClientModel) X509Certificate(java.security.cert.X509Certificate) Arrays(java.util.Arrays) X500Principal(javax.security.auth.x500.X500Principal) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) HashMap(java.util.HashMap) ServicesLogger(org.keycloak.services.ServicesLogger) ClientAuthenticationFlowContext(org.keycloak.authentication.ClientAuthenticationFlowContext) Function(java.util.function.Function) HashSet(java.util.HashSet) MediaType(javax.ws.rs.core.MediaType) GeneralSecurityException(java.security.GeneralSecurityException) AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) Map(java.util.Map) AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) Set(java.util.Set) Collectors(java.util.stream.Collectors) X509ClientCertificateLookup(org.keycloak.services.x509.X509ClientCertificateLookup) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) Response(javax.ws.rs.core.Response) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) OAuth2Constants(org.keycloak.OAuth2Constants) Pattern(java.util.regex.Pattern) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) GeneralSecurityException(java.security.GeneralSecurityException) X509ClientCertificateLookup(org.keycloak.services.x509.X509ClientCertificateLookup) X509Certificate(java.security.cert.X509Certificate) Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) MediaType(javax.ws.rs.core.MediaType) X500Principal(javax.security.auth.x500.X500Principal)

Aggregations

MediaType (javax.ws.rs.core.MediaType)477 Test (org.junit.Test)184 Path (javax.ws.rs.Path)44 Produces (javax.ws.rs.Produces)44 ByteArrayInputStream (java.io.ByteArrayInputStream)42 WebApplicationException (javax.ws.rs.WebApplicationException)41 IOException (java.io.IOException)40 Response (javax.ws.rs.core.Response)40 InputStream (java.io.InputStream)38 ArrayList (java.util.ArrayList)31 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)31 Type (java.lang.reflect.Type)30 Consumes (javax.ws.rs.Consumes)27 MultivaluedMap (javax.ws.rs.core.MultivaluedMap)27 GET (javax.ws.rs.GET)25 OutputStream (java.io.OutputStream)23 Annotation (java.lang.annotation.Annotation)23 HashSet (java.util.HashSet)22 Locale (java.util.Locale)22 HashMap (java.util.HashMap)21