Search in sources :

Example 16 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException in project graylog2-server by Graylog2.

the class ShiroAuthenticationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final SecurityContext securityContext = requestContext.getSecurityContext();
    if (securityContext instanceof ShiroSecurityContext) {
        final ShiroSecurityContext context = (ShiroSecurityContext) securityContext;
        final Subject subject = context.getSubject();
        LOG.trace("Authenticating... {}", subject);
        if (!subject.isAuthenticated()) {
            try {
                LOG.trace("Logging in {}", subject);
                context.loginSubject();
            } catch (LockedAccountException e) {
                LOG.debug("Unable to authenticate user, account is locked.", e);
                throw new NotAuthorizedException(e, "Basic realm=\"Graylog Server\"");
            } catch (AuthenticationException e) {
                LOG.debug("Unable to authenticate user.", e);
                throw new NotAuthorizedException(e, "Basic realm=\"Graylog Server\"");
            }
        }
    } else {
        throw new NotAuthorizedException("Basic realm=\"Graylog Server\"");
    }
}
Also used : AuthenticationException(org.apache.shiro.authc.AuthenticationException) SecurityContext(javax.ws.rs.core.SecurityContext) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Subject(org.apache.shiro.subject.Subject) LockedAccountException(org.apache.shiro.authc.LockedAccountException)

Example 17 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException in project keywhiz by square.

the class ClientAuthFactory method doProvide.

private Client doProvide(ContainerRequest containerRequest, HttpServletRequest httpServletRequest) {
    // Check whether this port is configured to be used by a proxy.
    // If this configuration is present, traffic on this port _must_
    // identify its clients using the x-forwarded-client-cert header or
    // caller ID header.
    // If the configuration is not present, traffic _must_ identify its
    // clients using the request's security context.
    int requestPort = httpServletRequest.getLocalPort();
    Optional<XfccSourceConfig> possibleXfccConfig = getXfccConfigForPort(requestPort);
    List<String> xfccHeaderValues = Optional.ofNullable(containerRequest.getRequestHeader(XFCC_HEADER_NAME)).orElse(List.of());
    // the callerSpiffeIdHeader identifies the client.)
    if (possibleXfccConfig.isEmpty() != xfccHeaderValues.isEmpty()) {
        throw new NotAuthorizedException(format("Port %d is configured to %s receive traffic with the %s header set", requestPort, possibleXfccConfig.isEmpty() ? "never" : "only", XFCC_HEADER_NAME));
    }
    // Extract information about the entity that connected directly to Keywhiz.
    // This must be identified from the request's security context, rather than
    // easily modified information like a header.
    // 
    // This entity may be a Keywhiz client, or it may be a proxy
    // forwarding the real Keywhiz client information.
    Principal connectedPrincipal = getPrincipal(containerRequest).orElseThrow(() -> new NotAuthorizedException("Not authorized as Keywhiz client"));
    setTag("principal", connectedPrincipal.getName());
    // on the security context of this request
    if (possibleXfccConfig.isEmpty()) {
        // identify the client
        return authenticateClientFromPrincipal(connectedPrincipal);
    } else {
        // Use either the XFCC header or a caller-ID header to identify the client.
        return authenticateClientFromForwardedData(possibleXfccConfig.get(), xfccHeaderValues, connectedPrincipal, containerRequest);
    }
}
Also used : XfccSourceConfig(keywhiz.service.config.XfccSourceConfig) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) SpiffePrincipal(keywhiz.auth.mutualssl.SpiffePrincipal) CertificatePrincipal(keywhiz.auth.mutualssl.CertificatePrincipal) Principal(java.security.Principal)

Example 18 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException in project keywhiz by square.

the class ClientAuthenticator method authenticate.

/**
 * Retrieve a client based on the name and/or SPIFFE ID included in the given
 * principal.
 *
 * @param principal an identification for a client in Keywhiz
 * @param createMissingClient whether to create the client (with no secrets or
 *                            groups assigned) if it does not exist
 * @return the requested client, or Optional.empty() if it does not
 * exist and createMissingClient was not set
 */
public Optional<Client> authenticate(Principal principal, boolean createMissingClient) {
    // Try to retrieve clients based on the client name and SPIFFE ID
    Optional<String> possibleClientName = getClientName(principal);
    Optional<URI> possibleClientSpiffeId = getSpiffeId(principal);
    Optional<Client> possibleClientFromName = possibleClientName.flatMap((name) -> {
        if (clientAuthConfig.typeConfig().useCommonName()) {
            return clientDAOReadOnly.getClientByName(name);
        } else {
            return Optional.empty();
        }
    });
    Optional<Client> possibleClientFromSpiffeId = possibleClientSpiffeId.flatMap((spiffeId) -> {
        if (clientAuthConfig.typeConfig().useSpiffeId()) {
            return clientDAOReadOnly.getClientBySpiffeId(spiffeId);
        } else {
            return Optional.empty();
        }
    });
    // check will not reject a certificate with a mismatched CN and SPIFFE URI.)
    if (possibleClientFromName.isPresent() && possibleClientFromSpiffeId.isPresent()) {
        if (!possibleClientFromName.get().equals(possibleClientFromSpiffeId.get())) {
            throw new NotAuthorizedException(format("Input principal's CN and SPIFFE ID correspond to different clients! (cn = %s, spiffe = %s)", possibleClientFromName.get().getName(), possibleClientFromSpiffeId.get().getName()));
        }
    } else if (possibleClientFromName.isEmpty() && possibleClientFromSpiffeId.isEmpty()) {
        // Create missing clients if configured to do so (client name must be present)
        return handleMissingClient(createMissingClient, possibleClientName.orElse(""), possibleClientSpiffeId);
    }
    // Retrieve whichever of the clients is set (if both are present, the earlier check guarantees
    // that they contain the same client).
    Client client = possibleClientFromName.or(() -> possibleClientFromSpiffeId).orElseThrow(() -> new IllegalStateException("Unable to identify client, and fallback code in server did not handle this case"));
    // Record that this client has been retrieved
    clientDAOReadWrite.sawClient(client, principal);
    if (client.isEnabled()) {
        return Optional.of(client);
    } else {
        logger.warn("Client {} authenticated but disabled via DB", client);
        return Optional.empty();
    }
}
Also used : NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Client(keywhiz.api.model.Client) URI(java.net.URI)

Example 19 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException in project cxf by apache.

the class OAuthInvoker method performInvocation.

@Override
protected Object performInvocation(Exchange exchange, final Object serviceObject, Method m, Object[] paramArray) throws Exception {
    Message inMessage = exchange.getInMessage();
    ClientTokenContext tokenContext = inMessage.getContent(ClientTokenContext.class);
    try {
        if (tokenContext != null) {
            StaticClientTokenContext.setClientTokenContext(tokenContext);
        }
        return super.performInvocation(exchange, serviceObject, m, paramArray);
    } catch (InvocationTargetException ex) {
        if (tokenContext != null && ex.getCause() instanceof NotAuthorizedException && !inMessage.containsKey(OAUTH2_CALL_RETRIED)) {
            ClientAccessToken accessToken = tokenContext.getToken();
            String refreshToken = accessToken.getRefreshToken();
            if (refreshToken != null) {
                accessToken = OAuthClientUtils.refreshAccessToken(accessTokenServiceClient, consumer, accessToken);
                validateRefreshedToken(tokenContext, accessToken);
                MessageContext mc = new MessageContextImpl(inMessage);
                ((ClientTokenContextImpl) tokenContext).setToken(accessToken);
                clientTokenContextManager.setClientTokenContext(mc, tokenContext);
                // retry
                inMessage.put(OAUTH2_CALL_RETRIED, true);
                return super.performInvocation(exchange, serviceObject, m, paramArray);
            }
        }
        throw ex;
    } finally {
        if (tokenContext != null) {
            StaticClientTokenContext.removeClientTokenContext();
        }
    }
}
Also used : Message(org.apache.cxf.message.Message) ClientAccessToken(org.apache.cxf.rs.security.oauth2.common.ClientAccessToken) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) InvocationTargetException(java.lang.reflect.InvocationTargetException) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Example 20 with NotAuthorizedException

use of javax.ws.rs.NotAuthorizedException in project cxf by apache.

the class AccessTokenValidatorService method getTokenValidationInfo.

@POST
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public AccessTokenValidation getTokenValidationInfo(@Encoded MultivaluedMap<String, String> params) {
    checkSecurityContext();
    String authScheme = params.getFirst(OAuthConstants.AUTHORIZATION_SCHEME_TYPE);
    String authSchemeData = params.getFirst(OAuthConstants.AUTHORIZATION_SCHEME_DATA);
    try {
        return super.getAccessTokenValidation(authScheme, authSchemeData, params);
    } catch (NotAuthorizedException ex) {
        // at this point it does not mean that RS failed to authenticate but that the basic
        // local or chained token validation has failed
        AccessTokenValidation v = new AccessTokenValidation();
        v.setInitialValidationSuccessful(false);
        return v;
    }
}
Also used : AccessTokenValidation(org.apache.cxf.rs.security.oauth2.common.AccessTokenValidation) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Aggregations

NotAuthorizedException (javax.ws.rs.NotAuthorizedException)28 ForbiddenException (javax.ws.rs.ForbiddenException)5 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)5 POST (javax.ws.rs.POST)5 Response (javax.ws.rs.core.Response)5 NotFoundException (javax.ws.rs.NotFoundException)4 SecurityContext (javax.ws.rs.core.SecurityContext)4 ApiOperation (io.swagger.annotations.ApiOperation)3 BadRequestException (javax.ws.rs.BadRequestException)3 Produces (javax.ws.rs.Produces)3 ServiceUnavailableException (javax.ws.rs.ServiceUnavailableException)3 Session (org.apache.shiro.session.Session)3 Subject (org.apache.shiro.subject.Subject)3 AuthenticationException (io.dropwizard.auth.AuthenticationException)2 IOException (java.io.IOException)2 URI (java.net.URI)2 NotAcceptableException (javax.ws.rs.NotAcceptableException)2 NotAllowedException (javax.ws.rs.NotAllowedException)2 NotSupportedException (javax.ws.rs.NotSupportedException)2 WebApplicationException (javax.ws.rs.WebApplicationException)2