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\"");
}
}
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);
}
}
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();
}
}
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();
}
}
}
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;
}
}
Aggregations