use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.
the class SecurityAuthenticationHttpHandler method validateSecuredInterception.
/**
* Intercepts the HttpMessage for getting the access token in authorization header
*
* @param ctx channel handler context delegated from MessageReceived callback
* @param msg intercepted HTTP message
* @param inboundChannel
* @return {@code true} if the HTTP message has valid Access token
* @throws Exception
*/
private boolean validateSecuredInterception(ChannelHandlerContext ctx, HttpRequest msg, Channel inboundChannel, AuditLogEntry logEntry) throws Exception {
String auth = msg.getHeader(HttpHeaders.Names.AUTHORIZATION);
String accessToken = null;
/*
* Parse the access token from authorization header. The header will be in the form:
* Authorization: Bearer ACCESSTOKEN
*
* where ACCESSTOKEN is the base64 encoded serialized AccessToken instance.
*/
if (auth != null) {
int spIndex = auth.trim().indexOf(' ');
if (spIndex != -1) {
accessToken = auth.substring(spIndex + 1).trim();
}
}
HttpMethod httpMethod = msg.getMethod();
String uri = msg.getUri();
logEntry.setClientIP(((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress());
logEntry.setRequestLine(httpMethod, uri, msg.getProtocolVersion());
TokenState tokenState = tokenValidator.validate(accessToken);
if (!tokenState.isValid()) {
HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
logEntry.setResponseCode(HttpResponseStatus.UNAUTHORIZED.getCode());
JsonObject jsonObject = new JsonObject();
if (tokenState == TokenState.MISSING) {
httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\"", realm));
LOG.debug("Authentication failed due to missing token");
} else {
httpResponse.addHeader(HttpHeaders.Names.WWW_AUTHENTICATE, String.format("Bearer realm=\"%s\" error=\"invalid_token\"" + " error_description=\"%s\"", realm, tokenState.getMsg()));
jsonObject.addProperty("error", "invalid_token");
jsonObject.addProperty("error_description", tokenState.getMsg());
LOG.debug("Authentication failed due to invalid token, reason={};", tokenState);
}
JsonArray externalAuthenticationURIs = new JsonArray();
// Waiting for service to get discovered
stopWatchWait(externalAuthenticationURIs);
jsonObject.add("auth_uri", externalAuthenticationURIs);
ChannelBuffer content = ChannelBuffers.wrappedBuffer(jsonObject.toString().getBytes(Charsets.UTF_8));
httpResponse.setContent(content);
int contentLength = content.readableBytes();
httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH, contentLength);
httpResponse.setHeader(HttpHeaders.Names.CONTENT_TYPE, "application/json;charset=UTF-8");
logEntry.setResponseContentLength(new Long(contentLength));
ChannelFuture writeFuture = Channels.future(inboundChannel);
Channels.write(ctx, writeFuture, httpResponse);
writeFuture.addListener(ChannelFutureListener.CLOSE);
return false;
} else {
AccessTokenTransformer.AccessTokenIdentifierPair accessTokenIdentifierPair = accessTokenTransformer.transform(accessToken);
AuditLogContent auditLogContent = AUDIT_LOG_LOOKUP_METHOD.contains(httpMethod) ? AUDIT_LOOK_UP.getAuditLogContent(msg.getUri(), httpMethod) : null;
if (auditLogContent != null) {
List<String> headerNames = auditLogContent.getHeaderNames();
if (!headerNames.isEmpty()) {
Map<String, String> headers = new HashMap<>();
for (String headerName : headerNames) {
headers.put(headerName, msg.getHeader(headerName));
}
logEntry.setHeaders(headers);
}
if (auditLogContent.isLogRequestBody()) {
ChannelBuffer body = msg.getContent();
if (body.readable()) {
logEntry.setRequestBody(body.toString(Charsets.UTF_8));
}
}
logEntry.setLogResponseBody(auditLogContent.isLogResponsebody());
}
logEntry.setUserName(accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
msg.setHeader(HttpHeaders.Names.AUTHORIZATION, "CDAP-verified " + accessTokenIdentifierPair.getAccessTokenIdentifierStr());
msg.setHeader(Constants.Security.Headers.USER_ID, accessTokenIdentifierPair.getAccessTokenIdentifierObj().getUsername());
msg.setHeader(Constants.Security.Headers.USER_IP, ((InetSocketAddress) ctx.getChannel().getRemoteAddress()).getAddress().getHostAddress());
return true;
}
}
use of org.jboss.netty.channel.ChannelFuture in project cdap by caskdata.
the class AuthenticationChannelHandler method exceptionCaught.
@Override
public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
LOG.error("Got exception: ", e.getCause());
ChannelFuture future = Channels.future(ctx.getChannel());
future.addListener(ChannelFutureListener.CLOSE);
// TODO: add WWW-Authenticate header for 401 response - REACTOR-900
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
Channels.write(ctx, future, response);
}
use of org.jboss.netty.channel.ChannelFuture in project dubbo by alibaba.
the class NettyClient method doConnect.
protected void doConnect() throws Throwable {
long start = System.currentTimeMillis();
ChannelFuture future = bootstrap.connect(getConnectAddress());
try {
boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
if (ret && future.isSuccess()) {
Channel newChannel = future.getChannel();
newChannel.setInterestOps(Channel.OP_READ_WRITE);
try {
// Close old channel
// copy reference
Channel oldChannel = NettyClient.this.channel;
if (oldChannel != null) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
}
oldChannel.close();
} finally {
NettyChannel.removeChannelIfDisconnected(oldChannel);
}
}
} finally {
if (NettyClient.this.isClosed()) {
try {
if (logger.isInfoEnabled()) {
logger.info("Close new netty channel " + newChannel + ", because the client closed.");
}
newChannel.close();
} finally {
NettyClient.this.channel = null;
NettyChannel.removeChannelIfDisconnected(newChannel);
}
} else {
NettyClient.this.channel = newChannel;
}
}
} else if (future.getCause() != null) {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
} else {
throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server " + getRemoteAddress() + " client-side timeout " + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client " + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
}
} finally {
if (!isConnected()) {
future.cancel();
}
}
}
use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.
the class OslpChannelHandler method send.
public OslpEnvelope send(final InetSocketAddress address, final OslpEnvelope request, final String deviceIdentification) throws IOException, DeviceSimulatorException {
LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
final Callback callback = new Callback(this.connectionTimeout);
this.lock.lock();
// Open connection and send message
ChannelFuture channelFuture = null;
try {
channelFuture = this.bootstrap.connect(address);
channelFuture.awaitUninterruptibly(this.connectionTimeout, TimeUnit.MILLISECONDS);
if (channelFuture.getChannel() != null && channelFuture.getChannel().isConnected()) {
LOGGER.info("Connection established to: {}", address);
} else {
LOGGER.info("The connnection to the device {} is not successfull", deviceIdentification);
LOGGER.warn("Unable to connect to: {}", address);
throw new IOException("Unable to connect");
}
this.callbacks.put(channelFuture.getChannel().getId(), callback);
channelFuture.getChannel().write(request);
} finally {
this.lock.unlock();
}
// wait for response and close connection
try {
final OslpEnvelope response = callback.get(deviceIdentification);
LOGGER.info("Received OSLP response (after callback): {}", response.getPayloadMessage());
/*
* Devices expect the channel to be closed if (and only if) the
* platform initiated the conversation. If the device initiated the
* conversation it needs to close the channel itself.
*/
channelFuture.getChannel().close();
return response;
} catch (final IOException | DeviceSimulatorException e) {
LOGGER.error("send exception", e);
// Remove callback when exception has occurred
this.callbacks.remove(channelFuture.getChannel().getId());
throw e;
}
}
use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.
the class OslpChannelHandlerClient method send.
public void send(final InetSocketAddress address, final OslpEnvelope request, final OslpResponseHandler responseHandler, final String deviceIdentification) throws IOException {
LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
// Open connection and send message.
final ChannelFuture channelFuture = this.bootstrap.connect(address);
this.callbackHandlers.put(channelFuture.getChannel().getId(), new OslpCallbackHandler(responseHandler));
channelFuture.addListener(new ChannelFutureListener() {
@Autowired
protected DeviceResponseMessageSender responseMessageSender;
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess()) {
OslpChannelHandlerClient.this.write(future, address, request);
// What is this call below good for?
future.getChannel().getId();
} else {
LOGGER.info("The connection to the device {} is not successful", deviceIdentification);
throw new IOException("ChannelFuture - Unable to connect");
}
}
});
}
Aggregations