Search in sources :

Example 36 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project traccar by tananaev.

the class SecurityRequestFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (requestContext.getMethod().equals("OPTIONS")) {
        return;
    }
    SecurityContext securityContext = null;
    try {
        String authHeader = requestContext.getHeaderString(AUTHORIZATION_HEADER);
        if (authHeader != null) {
            try {
                String[] auth = decodeBasicAuth(authHeader);
                User user = Context.getPermissionsManager().login(auth[0], auth[1]);
                if (user != null) {
                    Main.getInjector().getInstance(StatisticsManager.class).registerRequest(user.getId());
                    securityContext = new UserSecurityContext(new UserPrincipal(user.getId()));
                }
            } catch (StorageException e) {
                throw new WebApplicationException(e);
            }
        } else if (request.getSession() != null) {
            Long userId = (Long) request.getSession().getAttribute(SessionResource.USER_ID_KEY);
            if (userId != null) {
                Context.getPermissionsManager().checkUserEnabled(userId);
                Main.getInjector().getInstance(StatisticsManager.class).registerRequest(userId);
                securityContext = new UserSecurityContext(new UserPrincipal(userId));
            }
        }
    } catch (SecurityException e) {
        LOGGER.warn("Authentication error", e);
    }
    if (securityContext != null) {
        requestContext.setSecurityContext(securityContext);
    } else {
        Method method = resourceInfo.getResourceMethod();
        if (!method.isAnnotationPresent(PermitAll.class)) {
            Response.ResponseBuilder responseBuilder = Response.status(Response.Status.UNAUTHORIZED);
            if (!XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) {
                responseBuilder.header(WWW_AUTHENTICATE, BASIC_REALM);
            }
            throw new WebApplicationException(responseBuilder.build());
        }
    }
}
Also used : User(org.traccar.model.User) WebApplicationException(javax.ws.rs.WebApplicationException) Method(java.lang.reflect.Method) Response(javax.ws.rs.core.Response) StatisticsManager(org.traccar.database.StatisticsManager) SecurityContext(javax.ws.rs.core.SecurityContext) PermitAll(javax.annotation.security.PermitAll) StorageException(org.traccar.storage.StorageException)

Example 37 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project cxf by apache.

the class JAXRSUtils method createContextValue.

public static <T> T createContextValue(Message m, Type genericType, Class<T> clazz) {
    Message contextMessage = getContextMessage(m);
    Object o = null;
    if (UriInfo.class.isAssignableFrom(clazz)) {
        o = createUriInfo(contextMessage);
    } else if (HttpHeaders.class.isAssignableFrom(clazz) || ProtocolHeaders.class.isAssignableFrom(clazz)) {
        o = createHttpHeaders(contextMessage, clazz);
    } else if (SecurityContext.class.isAssignableFrom(clazz)) {
        SecurityContext customContext = contextMessage.get(SecurityContext.class);
        o = customContext == null ? new SecurityContextImpl(contextMessage) : customContext;
    } else if (MessageContext.class.isAssignableFrom(clazz)) {
        o = new MessageContextImpl(m);
    } else if (ResourceInfo.class.isAssignableFrom(clazz)) {
        o = new ResourceInfoImpl(contextMessage);
    } else if (ResourceContext.class.isAssignableFrom(clazz)) {
        final OperationResourceInfo ori = contextMessage.getExchange().get(OperationResourceInfo.class);
        if (ori != null) {
            o = new ResourceContextImpl(contextMessage, ori);
        }
    } else if (Request.class.isAssignableFrom(clazz)) {
        o = new RequestImpl(contextMessage);
    } else if (Providers.class.isAssignableFrom(clazz)) {
        o = new ProvidersImpl(contextMessage);
    } else if (ContextResolver.class.isAssignableFrom(clazz)) {
        o = createContextResolver(genericType, contextMessage);
    } else if (Configuration.class.isAssignableFrom(clazz)) {
        o = ProviderFactory.getInstance(contextMessage).getConfiguration(contextMessage);
    } else if (Application.class.isAssignableFrom(clazz)) {
        ProviderInfo<?> providerInfo = (ProviderInfo<?>) contextMessage.getExchange().getEndpoint().get(Application.class.getName());
        o = providerInfo == null ? null : providerInfo.getProvider();
    } else if (contextMessage != null) {
        ContextProvider<?> provider = ProviderFactory.getInstance(contextMessage).createContextProvider(clazz, contextMessage);
        if (provider != null) {
            o = provider.createContext(contextMessage);
        }
    }
    if (o == null && contextMessage != null && !MessageUtils.isRequestor(contextMessage)) {
        o = HttpUtils.createServletResourceValue(contextMessage, clazz);
    }
    return clazz.cast(o);
}
Also used : SecurityContextImpl(org.apache.cxf.jaxrs.impl.SecurityContextImpl) ResourceContext(javax.ws.rs.container.ResourceContext) Message(org.apache.cxf.message.Message) Configuration(javax.ws.rs.core.Configuration) ResourceInfoImpl(org.apache.cxf.jaxrs.impl.ResourceInfoImpl) ContextProvider(org.apache.cxf.jaxrs.ext.ContextProvider) Providers(javax.ws.rs.ext.Providers) ProvidersImpl(org.apache.cxf.jaxrs.impl.ProvidersImpl) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) SecurityContext(javax.ws.rs.core.SecurityContext) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) ResourceContextImpl(org.apache.cxf.jaxrs.impl.ResourceContextImpl) RequestImpl(org.apache.cxf.jaxrs.impl.RequestImpl) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 38 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project cxf by apache.

the class AbstractTokenService method authenticateClientIfNeeded.

/**
 * Make sure the client is authenticated
 */
protected Client authenticateClientIfNeeded(MultivaluedMap<String, String> params) {
    Client client = null;
    SecurityContext sc = getMessageContext().getSecurityContext();
    Principal principal = sc.getUserPrincipal();
    String clientId = retrieveClientId(params);
    if (principal == null) {
        if (clientId != null) {
            String clientSecret = params.getFirst(OAuthConstants.CLIENT_SECRET);
            if (clientSecret != null) {
                client = getAndValidateClientFromIdAndSecret(clientId, clientSecret, params);
                validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_POST);
            } else if (OAuthUtils.isMutualTls(sc, getTlsSessionInfo())) {
                client = getClient(clientId, params);
                checkCertificateBinding(client, getTlsSessionInfo());
                validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS);
            } else if (canSupportPublicClients) {
                client = getValidClient(clientId, params);
                if (!isValidPublicClient(client, clientId)) {
                    client = null;
                } else {
                    validateClientAuthenticationMethod(client, OAuthConstants.TOKEN_ENDPOINT_AUTH_NONE);
                }
            }
        }
    } else {
        if (clientId != null) {
            if (!clientId.equals(principal.getName())) {
                reportInvalidClient();
            }
            client = (Client) getMessageContext().get(Client.class.getName());
            if (client == null) {
                client = getClient(clientId, params);
            }
        } else if (principal.getName() != null) {
            client = getClient(principal.getName(), params);
        }
    }
    if (client == null) {
        client = getClientFromTLSCertificates(sc, getTlsSessionInfo(), params);
        if (client == null) {
            // Basic Authentication is expected by default
            client = getClientFromBasicAuthScheme(params);
        }
    }
    if (client == null) {
        reportInvalidClient();
    }
    return client;
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext) Client(org.apache.cxf.rs.security.oauth2.common.Client) Principal(java.security.Principal)

Example 39 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project cxf by apache.

the class DynamicRegistrationService method createNewClient.

protected Client createNewClient(ClientRegistration request) {
    // Client ID
    String clientId = generateClientId();
    // Client Name
    String clientName = request.getClientName();
    if (StringUtils.isEmpty(clientName)) {
        clientName = clientId;
    }
    List<String> grantTypes = request.getGrantTypes();
    if (grantTypes == null) {
        grantTypes = Collections.singletonList(OAuthConstants.AUTHORIZATION_CODE_GRANT);
    }
    String tokenEndpointAuthMethod = request.getTokenEndpointAuthMethod();
    // TODO: default is expected to be set to OAuthConstants.TOKEN_ENDPOINT_AUTH_BASIC
    boolean passwordRequired = isPasswordRequired(grantTypes, tokenEndpointAuthMethod);
    // Application Type
    // https://tools.ietf.org/html/rfc7591 has no this property but
    // but http://openid.net/specs/openid-connect-registration-1_0.html#ClientMetadata does
    String appType = request.getApplicationType();
    if (appType == null) {
        appType = DEFAULT_APPLICATION_TYPE;
    }
    boolean isConfidential = DEFAULT_APPLICATION_TYPE.equals(appType) && (passwordRequired || OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod));
    // Client Secret
    String clientSecret = passwordRequired ? generateClientSecret(request) : null;
    Client newClient = new Client(clientId, clientSecret, isConfidential, clientName);
    newClient.setAllowedGrantTypes(grantTypes);
    newClient.setTokenEndpointAuthMethod(tokenEndpointAuthMethod);
    if (OAuthConstants.TOKEN_ENDPOINT_AUTH_TLS.equals(tokenEndpointAuthMethod)) {
        String subjectDn = (String) request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN);
        if (subjectDn != null) {
            newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_SUBJECT_DN, subjectDn);
        }
        String issuerDn = (String) request.getProperty(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN);
        if (issuerDn != null) {
            newClient.getProperties().put(OAuthConstants.TLS_CLIENT_AUTH_ISSUER_DN, issuerDn);
        }
    }
    // Client Registration Time
    newClient.setRegisteredAt(System.currentTimeMillis() / 1000L);
    fromClientRegistrationToClient(request, newClient);
    SecurityContext sc = mc.getSecurityContext();
    if (sc != null && sc.getUserPrincipal() != null && sc.getUserPrincipal().getName() != null) {
        UserSubject subject = new UserSubject(sc.getUserPrincipal().getName());
        newClient.setResourceOwnerSubject(subject);
    }
    newClient.setRegisteredDynamically(true);
    return newClient;
}
Also used : UserSubject(org.apache.cxf.rs.security.oauth2.common.UserSubject) SecurityContext(javax.ws.rs.core.SecurityContext) Client(org.apache.cxf.rs.security.oauth2.common.Client)

Example 40 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project cxf by apache.

the class ClientCodeRequestFilter method checkSecurityContextEnd.

private void checkSecurityContextEnd(ContainerRequestContext rc, MultivaluedMap<String, String> requestParams) {
    SecurityContext sc = rc.getSecurityContext();
    if (sc == null || sc.getUserPrincipal() == null) {
        String codeParam = requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE);
        if (codeParam == null && requestParams.containsKey(OAuthConstants.ERROR_KEY) && !faultAccessDeniedResponses) {
            if (!applicationCanHandleAccessDenied) {
                String error = requestParams.getFirst(OAuthConstants.ERROR_KEY);
                rc.abortWith(Response.ok(new AccessDeniedResponse(error)).build());
            }
        } else {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext)

Aggregations

SecurityContext (javax.ws.rs.core.SecurityContext)77 Response (javax.ws.rs.core.Response)30 Context (javax.ws.rs.core.Context)18 Test (org.junit.Test)18 List (java.util.List)17 Principal (java.security.Principal)16 LoggerFactory (org.slf4j.LoggerFactory)16 Logger (org.slf4j.Logger)12 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 Path (javax.ws.rs.Path)11 IOException (java.io.IOException)10 POST (javax.ws.rs.POST)8 LocalPasswordHandler (com.emc.storageos.systemservices.impl.util.LocalPasswordHandler)6 GET (javax.ws.rs.GET)6 PathParam (javax.ws.rs.PathParam)6 Produces (javax.ws.rs.Produces)6 MediaType (javax.ws.rs.core.MediaType)6 Status (javax.ws.rs.core.Response.Status)6 UriInfo (javax.ws.rs.core.UriInfo)6