Search in sources :

Example 96 with MediaType

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

the class ClientIdAndSecretAuthenticator method authenticateClient.

@Override
public void authenticateClient(ClientAuthenticationFlowContext context) {
    String client_id = null;
    String clientSecret = null;
    String authorizationHeader = context.getHttpRequest().getHttpHeaders().getRequestHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    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;
    if (authorizationHeader != null) {
        String[] usernameSecret = BasicAuthHelper.parseHeader(authorizationHeader);
        if (usernameSecret != null) {
            client_id = usernameSecret[0];
            clientSecret = usernameSecret[1];
        } else {
            // Don't send 401 if client_id parameter was sent in request. For example IE may automatically send "Authorization: Negotiate" in XHR requests even for public clients
            if (formData != null && !formData.containsKey(OAuth2Constants.CLIENT_ID)) {
                Response challengeResponse = Response.status(Response.Status.UNAUTHORIZED).header(HttpHeaders.WWW_AUTHENTICATE, "Basic realm=\"" + context.getRealm().getName() + "\"").build();
                context.challenge(challengeResponse);
                return;
            }
        }
    }
    if (formData != null) {
        // so we can also support clients overriding flows and using challenges (e.g: basic) to authenticate their users
        if (formData.containsKey(OAuth2Constants.CLIENT_ID)) {
            client_id = formData.getFirst(OAuth2Constants.CLIENT_ID);
        }
        if (formData.containsKey(OAuth2Constants.CLIENT_SECRET)) {
            clientSecret = formData.getFirst(OAuth2Constants.CLIENT_SECRET);
        }
    }
    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;
    }
    context.getEvent().client(client_id);
    ClientModel client = context.getSession().clients().getClientByClientId(context.getRealm(), client_id);
    if (client == null) {
        context.failure(AuthenticationFlowError.CLIENT_NOT_FOUND, null);
        return;
    }
    context.setClient(client);
    if (!client.isEnabled()) {
        context.failure(AuthenticationFlowError.CLIENT_DISABLED, null);
        return;
    }
    // Skip client_secret validation for public client
    if (client.isPublicClient()) {
        context.success();
        return;
    }
    if (clientSecret == null) {
        Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "unauthorized_client", "Client secret not provided in request");
        context.challenge(challengeResponse);
        return;
    }
    if (client.getSecret() == null) {
        Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "unauthorized_client", "Invalid client secret");
        context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
        return;
    }
    if (!client.validateSecret(clientSecret)) {
        Response challengeResponse = ClientAuthUtil.errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "unauthorized_client", "Invalid client secret");
        context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS, challengeResponse);
        return;
    }
    context.success();
}
Also used : Response(javax.ws.rs.core.Response) ClientModel(org.keycloak.models.ClientModel) MediaType(javax.ws.rs.core.MediaType)

Example 97 with MediaType

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

the class CsrfFilter method filter.

@Override
public void filter(final ContainerRequestContext requestContext) throws IOException {
    if (!requestContext.getMethod().equals("POST")) {
        return;
    }
    final MinijaxRequestContext ctx = (MinijaxRequestContext) requestContext;
    final Security<?> security = ctx.get(Security.class);
    if (!security.isLoggedIn() || security.getAuthenticationScheme() != SecurityContext.FORM_AUTH) {
        return;
    }
    final MediaType contentType = ctx.getMediaType();
    if (contentType == null) {
        return;
    }
    if (!contentType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE) && !contentType.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
        return;
    }
    security.validateSession(ctx.getForm().getString("csrf"));
}
Also used : MinijaxRequestContext(org.minijax.MinijaxRequestContext) MediaType(javax.ws.rs.core.MediaType)

Example 98 with MediaType

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

the class MinijaxApplication method write.

@SuppressWarnings({ "rawtypes", "unchecked" })
public void write(final MinijaxRequestContext context, final Response response, final HttpServletResponse servletResponse) throws IOException {
    servletResponse.setStatus(response.getStatus());
    for (final Entry<String, List<Object>> entry : response.getHeaders().entrySet()) {
        final String name = entry.getKey();
        for (final Object value : entry.getValue()) {
            servletResponse.addHeader(name, value.toString());
        }
    }
    if (context.getMethod().equals("OPTIONS")) {
        return;
    }
    final MediaType mediaType = response.getMediaType();
    if (mediaType != null) {
        servletResponse.setContentType(mediaType.toString());
    }
    final Object obj = response.getEntity();
    if (obj == null) {
        return;
    }
    final MessageBodyWriter writer = providers.getMessageBodyWriter(obj.getClass(), null, null, mediaType);
    if (writer != null) {
        writer.writeTo(obj, obj.getClass(), null, null, mediaType, null, servletResponse.getOutputStream());
        return;
    }
    // What to do
    servletResponse.getWriter().println(obj.toString());
}
Also used : MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 99 with MediaType

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

the class MinijaxApplication method getParamProviders.

/**
 * Returns the param providers for a resource method.
 *
 * This is very similar to the logic used in building param providers for a normal
 * <code>@Inject</code> constructor, with one major difference.
 *
 * A resource method is allowed one special "entity" parameter representing the content body.
 * This entity parameter is handled by a <code>EntityProvider</code>.
 *
 * @param method The resource method.
 * @return The array of resource method param providers.
 */
private Provider<?>[] getParamProviders(final Method method) {
    final Class<?>[] paramClasses = method.getParameterTypes();
    final Type[] paramTypes = method.getGenericParameterTypes();
    final Annotation[][] annotations = method.getParameterAnnotations();
    final Provider<?>[] result = new Provider<?>[paramTypes.length];
    final Consumes consumes = method.getAnnotation(Consumes.class);
    final List<MediaType> consumesTypes = MediaTypeUtils.parseMediaTypes(consumes);
    boolean consumed = false;
    for (int i = 0; i < paramTypes.length; i++) {
        if (annotations[i].length == 0 && !consumed) {
            result[i] = new EntityProvider<>(paramClasses[i], paramTypes[i], annotations[i], consumesTypes);
            consumed = true;
        } else {
            result[i] = getInjector().getProvider(paramClasses[i], annotations[i]);
        }
    }
    return result;
}
Also used : Provider(javax.inject.Provider) EntityProvider(org.minijax.cdi.EntityProvider) MediaType(javax.ws.rs.core.MediaType) RuntimeType(javax.ws.rs.RuntimeType) Type(java.lang.reflect.Type) Consumes(javax.ws.rs.Consumes) MediaType(javax.ws.rs.core.MediaType)

Example 100 with MediaType

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

the class EntityProvider method getImpl.

@SuppressWarnings("unchecked")
private T getImpl(final MinijaxRequestContext context, final InputStream entityStream) throws IOException {
    if (entityClass == String.class) {
        return (T) IOUtils.toString(entityStream, StandardCharsets.UTF_8);
    }
    if (entityClass == MultivaluedMap.class) {
        return (T) context.getForm().asForm().asMap();
    }
    final MediaType mediaType = consumesTypes != null && !consumesTypes.isEmpty() ? consumesTypes.get(0) : null;
    final MessageBodyReader<T> reader = context.getApplication().getProviders().getMessageBodyReader(entityClass, genericType, annotations, mediaType);
    if (reader != null) {
        final MultivaluedMap<String, String> httpHeaders = context.getHeaders();
        return reader.readFrom(entityClass, genericType, annotations, mediaType, httpHeaders, entityStream);
    }
    throw new InjectionException("Unknown entity type (" + entityClass + ")");
}
Also used : InjectionException(javax.enterprise.inject.InjectionException) MediaType(javax.ws.rs.core.MediaType)

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