Example usage for io.netty.handler.codec.http HttpResponseStatus UNAUTHORIZED

List of usage examples for io.netty.handler.codec.http HttpResponseStatus UNAUTHORIZED

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseStatus UNAUTHORIZED.

Prototype

HttpResponseStatus UNAUTHORIZED

To view the source code for io.netty.handler.codec.http HttpResponseStatus UNAUTHORIZED.

Click Source Link

Document

401 Unauthorized

Usage

From source file:cf.service.NettyBrokerServer.java

License:Open Source License

private void validateAuthToken(HttpRequest request) throws RequestException {
    final String authToken = request.headers().get(VCAP_SERVICE_TOKEN_HEADER);
    if (!isValidAuthToken(authToken)) {
        throw new RequestException(HttpResponseStatus.UNAUTHORIZED);
    }//from   w  w w.  j  a v a2s .c o m
}

From source file:com.barchart.http.server.HttpRequestChannelHandler.java

License:BSD License

@Override
public void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest msg) throws Exception {

    final RequestHandlerMapping mapping = config.getRequestMapping(msg.getUri());

    String relativePath = msg.getUri();

    if (mapping != null) {
        relativePath = relativePath.substring(mapping.path().length());
    }//from   w w  w  .  ja v a 2  s .c  o  m

    // Create request/response
    final PooledServerRequest request = messagePool.getRequest();

    // Handle 503 - sanity check, should be caught in acceptor
    if (request == null) {
        sendServerError(ctx, new ServerTooBusyException("Maximum concurrent connections reached"));
        return;
    }

    request.init(ctx.channel(), msg, relativePath);

    final RequestHandler handler = mapping == null ? null : mapping.handler(request);

    final PooledServerResponse response = messagePool.getResponse();
    response.init(ctx, this, handler, request, config.logger());

    if (mapping == null) {
        // No handler found, 404
        response.setStatus(HttpResponseStatus.NOT_FOUND);
    }

    // Store in ChannelHandlerContext for future reference
    ctx.attr(ATTR_RESPONSE).set(response);

    try {

        // MJS: Dispatch an error if not found or authorized
        if (response.getStatus() == HttpResponseStatus.UNAUTHORIZED
                || response.getStatus() == HttpResponseStatus.NOT_FOUND) {
            config.errorHandler().onError(request, response, null);
        } else {
            handler.onRequest(request, response);
        }

    } catch (final Throwable t) {

        // Catch server errors
        response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);

        try {
            config.errorHandler().onError(request, response, t);
        } catch (final Throwable t2) {
            response.write(t.getClass() + " was thrown while processing this request.  Additionally, "
                    + t2.getClass() + " was thrown while handling this exception.");
        }

        config.logger().error(request, response, t);

        // Force request to end on exception, async handlers cannot allow
        // unchecked exceptions and still expect to return data
        if (!response.isFinished()) {
            response.finish();
        }

    } finally {

        // If handler did not request async response, finish request
        if (!response.isFinished() && !response.isSuspended()) {
            response.finish();
        }

    }

}

From source file:com.barchart.netty.rest.server.filter.RestAuthenticatorBase.java

License:BSD License

/**
 * Return a 401 Unauthorized message to the client.
 *//*w w w  .j av a 2  s.  c  o  m*/
protected void unauthorized(final HttpServerResponse response, final String message) throws IOException {
    response.headers().set(HttpHeaders.Names.WWW_AUTHENTICATE, "Basic realm=\"barchart.com\"");
    response.setStatus(HttpResponseStatus.UNAUTHORIZED);
    response.write(message);
    response.finish();
}

From source file:com.bloom.zerofs.rest.NettyResponseChannel.java

License:Open Source License

/**
 * Converts a {@link ResponseStatus} into a {@link HttpResponseStatus}.
 * @param responseStatus {@link ResponseStatus} that needs to be mapped to a {@link HttpResponseStatus}.
 * @return the {@link HttpResponseStatus} that maps to the {@link ResponseStatus}.
 *///from w w  w . j  a v  a 2 s.c om
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
    HttpResponseStatus status;
    switch (responseStatus) {
    case Ok:
        status = HttpResponseStatus.OK;
        break;
    case Created:
        status = HttpResponseStatus.CREATED;
        break;
    case Accepted:
        status = HttpResponseStatus.ACCEPTED;
        break;
    case NotModified:
        status = HttpResponseStatus.NOT_MODIFIED;
        break;
    case BadRequest:
        nettyMetrics.badRequestCount.inc();
        status = HttpResponseStatus.BAD_REQUEST;
        break;
    case Unauthorized:
        nettyMetrics.unauthorizedCount.inc();
        status = HttpResponseStatus.UNAUTHORIZED;
        break;
    case NotFound:
        nettyMetrics.notFoundCount.inc();
        status = HttpResponseStatus.NOT_FOUND;
        break;
    case Gone:
        nettyMetrics.goneCount.inc();
        status = HttpResponseStatus.GONE;
        break;
    case Forbidden:
        nettyMetrics.forbiddenCount.inc();
        status = HttpResponseStatus.FORBIDDEN;
        break;
    case ProxyAuthenticationRequired:
        nettyMetrics.proxyAuthRequiredCount.inc();
        status = HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
        break;
    case InternalServerError:
        nettyMetrics.internalServerErrorCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    default:
        nettyMetrics.unknownResponseStatusCount.inc();
        status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
        break;
    }
    return status;
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandler.java

License:Apache License

private boolean authorize(ChannelHandlerContext ctx, Channel channel, String origin,
        Map<String, List<String>> params, FullHttpRequest req) throws IOException {
    Map<String, List<String>> headers = new HashMap<String, List<String>>(req.headers().names().size());
    for (String name : req.headers().names()) {
        List<String> values = req.headers().getAll(name);
        headers.put(name, values);/*  w ww.j a  v a 2  s .  co m*/
    }

    HandshakeData data = new HandshakeData(headers, params, (InetSocketAddress) channel.remoteAddress(),
            req.getUri(), origin != null && !origin.equalsIgnoreCase("null"));

    boolean result = false;
    try {
        result = configuration.getAuthorizationListener().isAuthorized(data);
    } catch (Exception e) {
        log.error("Authorization error", e);
    }

    if (!result) {
        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        log.debug("Handshake unauthorized, query params: {} headers: {}", params, headers);
        return false;
    }

    UUID sessionId = this.generateOrGetSessionIdFromRequest(headers);

    List<String> transportValue = params.get("transport");
    if (transportValue == null) {
        log.warn("Got no transports for request {}", req.getUri());

        HttpResponse res = new DefaultHttpResponse(HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
        channel.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
        return false;
    }

    Transport transport = Transport.byName(transportValue.get(0));
    ClientHead client = new ClientHead(sessionId, ackManager, disconnectable, storeFactory, data, clientsBox,
            transport, disconnectScheduler, configuration);
    channel.attr(ClientHead.CLIENT).set(client);
    clientsBox.addClient(client);

    String[] transports = {};
    if (configuration.getTransports().contains(Transport.WEBSOCKET)) {
        transports = new String[] { "websocket" };
    }

    AuthPacket authPacket = new AuthPacket(sessionId, transports, configuration.getPingInterval(),
            configuration.getPingTimeout());
    Packet packet = new Packet(PacketType.OPEN);
    packet.setData(authPacket);
    client.send(packet);

    client.schedulePingTimeout();
    log.debug("Handshake authorized for sessionId: {}, query params: {} headers: {}", sessionId, params,
            headers);
    return true;
}

From source file:com.corundumstudio.socketio.handler.AuthorizeHandlerTest.java

License:Apache License

@Test
public void shouldNotAuthorizeRequest() throws Exception {
    prepareAuthorizationListener(false, null);

    channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, TEST_URI));
    // then// ww  w .j  a v  a 2 s. c o m
    Object out = channel.readOutbound();
    assertTrue(out instanceof DefaultHttpResponse);
    DefaultHttpResponse res = (DefaultHttpResponse) out;
    assertEquals(HttpResponseStatus.UNAUTHORIZED, res.getStatus());
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

License:Open Source License

/** See https://tools.ietf.org/html/rfc6750#section-3.1 */
private boolean authTokenExpired(HttpResponse response) {
    synchronized (credentialsLock) {
        if (creds == null) {
            return false;
        }//from w ww.  ja  v a 2s.  co m
    }
    List<String> values = response.headers().getAllAsString(HttpHeaderNames.WWW_AUTHENTICATE);
    String value = String.join(",", values);
    if (value != null && value.startsWith("Bearer")) {
        return INVALID_TOKEN_ERROR.matcher(value).find();
    } else {
        return response.status().equals(HttpResponseStatus.UNAUTHORIZED);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void errorCodeThatShouldNotBeRetried_get(ErrorType errorType) throws InterruptedException {
    ServerSocketChannel server = null;
    try {/*from  w ww  . j ava  2  s  .  co m*/
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        blobStore.get("key", new ByteArrayOutputStream());
        fail("Exception expected.");
    } catch (Exception e) {
        assertThat(e).isInstanceOf(HttpException.class);
        assertThat(((HttpException) e).response().status()).isEqualTo(HttpResponseStatus.UNAUTHORIZED);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStoreTest.java

License:Open Source License

private void errorCodeThatShouldNotBeRetried_put(ErrorType errorType) throws InterruptedException {
    ServerSocketChannel server = null;
    try {/*from w w w  . j a va2  s.  co m*/
        server = startServer(new NotAuthorizedHandler(errorType));
        int serverPort = server.localAddress().getPort();

        Credentials credentials = newCredentials();
        HttpBlobStore blobStore = new HttpBlobStore(new URI("http://localhost:" + serverPort), 30, credentials);
        blobStore.put("key", 1, new ByteArrayInputStream(new byte[] { 0 }));
        fail("Exception expected.");
    } catch (Exception e) {
        assertThat(e).isInstanceOf(HttpException.class);
        assertThat(((HttpException) e).response().status()).isEqualTo(HttpResponseStatus.UNAUTHORIZED);
    } finally {
        closeServerChannel(server);
    }
}

From source file:com.mastfrog.acteur.auth.AuthenticateBasicActeur.java

License:Open Source License

@Benchmark(value = "failedAuthentication", publish = Kind.CALL_COUNT)
private void unauthorized(Realm realm, HttpEvent evt, AuthenticationDecorator decorator, Page page,
        Response response) {//from   w  w w .  j a v a2  s. c o m
    decorator.onAuthenticationFailed(null, page, response);
    add(Headers.WWW_AUTHENTICATE, realm);
    setState(new RespondWith(HttpResponseStatus.UNAUTHORIZED));
    setResponseBodyWriter(ChannelFutureListener.CLOSE);
}