Java Code Examples for io.netty.handler.codec.http.HttpResponseStatus#UNAUTHORIZED

The following examples show how to use io.netty.handler.codec.http.HttpResponseStatus#UNAUTHORIZED . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: besu   File: GraphQLHttpService.java    License: Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus status(final GraphQLResponse response) {

    switch (response.getType()) {
      case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
      case ERROR:
        return HttpResponseStatus.BAD_REQUEST;
      case SUCCESS:
      case NONE:
      default:
        return HttpResponseStatus.OK;
    }
  }
 
Example 2
Source Project: besu   File: JsonRpcHttpService.java    License: Apache License 2.0 5 votes vote down vote up
private HttpResponseStatus status(final JsonRpcResponse response) {

    switch (response.getType()) {
      case UNAUTHORIZED:
        return HttpResponseStatus.UNAUTHORIZED;
      case ERROR:
        return HttpResponseStatus.BAD_REQUEST;
      case SUCCESS:
      case NONE:
      default:
        return HttpResponseStatus.OK;
    }
  }
 
Example 3
@Override
public boolean isAuthorized(ChannelHandlerContext ctx, FullHttpRequest req) {
   if(!sessionAuth.isAuthorized(ctx, req)) {
      logger.debug("session is not authorized, attempting to authenticate request");
      FullHttpResponse response = authenticator.authenticateRequest(ctx.channel(), req);
      logger.debug("response from authenticator is {}", response);
      return response != null && response.getStatus() != HttpResponseStatus.UNAUTHORIZED;
   }
   return true;
}
 
Example 4
Source Project: CloudNet   File: WebsiteAuthorization.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public FullHttpResponse get(ChannelHandlerContext channelHandlerContext,
                            QueryDecoder queryDecoder,
                            PathProvider path,
                            HttpRequest httpRequest) throws Exception {
    CloudNet.getLogger().debug("HTTP Request from " + channelHandlerContext.channel().remoteAddress());

    FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(httpRequest.getProtocolVersion(), HttpResponseStatus.UNAUTHORIZED);
    fullHttpResponse.headers().set("Content-Type", "application/json");
    fullHttpResponse.headers().set("Access-Control-Allow-Origin", "*");

    Document dataDocument = new Document("success", false).append("reason", new ArrayList<>()).append("response", new Document());
    if (!httpRequest.headers().contains("-Xcloudnet-user") || (!httpRequest.headers()
                                                                           .contains("-Xcloudnet-token") && !httpRequest.headers()
                                                                                                                        .contains(
                                                                                                                            "-Xcloudnet-password"))) {
        dataDocument.append("reason", Arrays.asList("-Xcloudnet-user, -Xcloudnet-token or -Xmessage not found!"));
        fullHttpResponse.content().writeBytes(dataDocument.convertToJsonString().getBytes(StandardCharsets.UTF_8));
        return fullHttpResponse;
    }

    if (httpRequest.headers().contains("-Xcloudnet-token") ? !CloudNet.getInstance().authorization(httpRequest.headers()
                                                                                                              .get("-Xcloudnet-user"),
                                                                                                   httpRequest.headers()
                                                                                                              .get("-Xcloudnet-token")) : !CloudNet
        .getInstance()
        .authorizationPassword(httpRequest.headers().get("-Xcloudnet-user"), httpRequest.headers().get("-Xcloudnet-password"))) {
        dataDocument.append("reason", Arrays.asList("failed authorization!"));
        fullHttpResponse.content().writeBytes(dataDocument.convertToJsonString().getBytes(StandardCharsets.UTF_8));
        return fullHttpResponse;
    }

    dataDocument.append("success", true);
    fullHttpResponse.content().writeBytes(dataDocument.convertToJsonString().getBytes(StandardCharsets.UTF_8));
    return fullHttpResponse;
}
 
Example 5
public static FullHttpResponse make(HttpResponseStatus status) {
    if (HttpResponseStatus.UNAUTHORIZED == status) {
        return NettyHttpResponse.make(HttpResponseStatus.UNAUTHORIZED, CONTENT_ERROR_401);
    }
    if (HttpResponseStatus.NOT_FOUND == status) {
        return NettyHttpResponse.make(HttpResponseStatus.NOT_FOUND, CONTENT_ERROR_404);
    }
    if (HttpResponseStatus.METHOD_NOT_ALLOWED == status) {
        return NettyHttpResponse.make(HttpResponseStatus.METHOD_NOT_ALLOWED, CONTENT_ERROR_405);
    }
    return NettyHttpResponse.make(HttpResponseStatus.OK,CONTENT_NORMAL_200);
}
 
Example 6
Source Project: arcusplatform   File: OAuthUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static FullHttpResponse unauthorized() {
   return new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.UNAUTHORIZED);
}
 
Example 7
Source Project: ambry   File: NettyResponseChannel.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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}.
 */
private HttpResponseStatus getHttpResponseStatus(ResponseStatus responseStatus) {
  HttpResponseStatus status;
  switch (responseStatus) {
    case Ok:
      nettyMetrics.okCount.inc();
      status = HttpResponseStatus.OK;
      break;
    case Created:
      nettyMetrics.createdCount.inc();
      status = HttpResponseStatus.CREATED;
      break;
    case Accepted:
      nettyMetrics.acceptedCount.inc();
      status = HttpResponseStatus.ACCEPTED;
      break;
    case PartialContent:
      nettyMetrics.partialContentCount.inc();
      status = HttpResponseStatus.PARTIAL_CONTENT;
      break;
    case NotModified:
      nettyMetrics.notModifiedCount.inc();
      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 Conflict:
      nettyMetrics.conflictCount.inc();
      status = HttpResponseStatus.CONFLICT;
      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 RangeNotSatisfiable:
      nettyMetrics.rangeNotSatisfiableCount.inc();
      status = HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
      break;
    case TooManyRequests:
      nettyMetrics.tooManyRequests.inc();
      status = HttpResponseStatus.TOO_MANY_REQUESTS;
      break;
    case RequestTooLarge:
      nettyMetrics.requestTooLargeCount.inc();
      status = HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
      break;
    case InternalServerError:
      nettyMetrics.internalServerErrorCount.inc();
      status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
      break;
    case ServiceUnavailable:
      nettyMetrics.serviceUnavailableErrorCount.inc();
      status = HttpResponseStatus.SERVICE_UNAVAILABLE;
      break;
    case InsufficientCapacity:
      nettyMetrics.insufficientCapacityErrorCount.inc();
      status = HttpResponseStatus.INSUFFICIENT_STORAGE;
      break;
    case PreconditionFailed:
      nettyMetrics.preconditionFailedErrorCount.inc();
      status = HttpResponseStatus.PRECONDITION_FAILED;
      break;
    case MethodNotAllowed:
      nettyMetrics.methodNotAllowedErrorCount.inc();
      status = HttpResponseStatus.METHOD_NOT_ALLOWED;
      break;
    default:
      nettyMetrics.unknownResponseStatusCount.inc();
      status = HttpResponseStatus.INTERNAL_SERVER_ERROR;
      break;
  }
  return status;
}
 
Example 8
Source Project: ambry   File: NettyResponseChannelTest.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @param code the {@link RestServiceErrorCode} whose {@link HttpResponseStatus} equivalent is required.
 * @return the {@link HttpResponseStatus} equivalent of {@code code}.
 */
private HttpResponseStatus getExpectedHttpResponseStatus(RestServiceErrorCode code) {
  switch (code) {
    case RequestTooLarge:
      return HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE;
    case Conflict:
      return HttpResponseStatus.CONFLICT;
    case Deleted:
      return HttpResponseStatus.GONE;
    case NotFound:
      return HttpResponseStatus.NOT_FOUND;
    case BadRequest:
    case InvalidArgs:
    case InvalidAccount:
    case InvalidContainer:
    case InvalidRequestState:
    case MalformedRequest:
    case MissingArgs:
    case UnsupportedHttpMethod:
      return HttpResponseStatus.BAD_REQUEST;
    case ResourceDirty:
    case AccessDenied:
      return HttpResponseStatus.FORBIDDEN;
    case Unauthorized:
      return HttpResponseStatus.UNAUTHORIZED;
    case ResourceScanInProgress:
      return HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED;
    case RangeNotSatisfiable:
      return HttpResponseStatus.REQUESTED_RANGE_NOT_SATISFIABLE;
    case ServiceUnavailable:
      return HttpResponseStatus.SERVICE_UNAVAILABLE;
    case TooManyRequests:
      return HttpResponseStatus.TOO_MANY_REQUESTS;
    case InsufficientCapacity:
      return HttpResponseStatus.INSUFFICIENT_STORAGE;
    case IdConverterServiceError:
    case InternalServerError:
    case RequestChannelClosed:
    case RequestResponseQueuingFailure:
    case UnsupportedRestMethod:
      return HttpResponseStatus.INTERNAL_SERVER_ERROR;
    case PreconditionFailed:
      return HttpResponseStatus.PRECONDITION_FAILED;
    case NotAllowed:
      return HttpResponseStatus.METHOD_NOT_ALLOWED;
    default:
      throw new IllegalArgumentException("Unrecognized RestServiceErrorCode - " + code);
  }
}
 
Example 9
Source Project: crate   File: SQLExceptions.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Create a {@link SQLActionException} out of a {@link Throwable}.
 * If concrete {@link ElasticsearchException} is found, first transform it
 * to a {@link CrateException}
 */
public static SQLActionException createSQLActionException(Throwable e, Consumer<Throwable> maskSensitiveInformation) {
    // ideally this method would be a static factory method in SQLActionException,
    // but that would pull too many dependencies for the client

    if (e instanceof SQLActionException) {
        return (SQLActionException) e;
    }
    Throwable unwrappedError = SQLExceptions.unwrap(e);
    e = esToCrateException(unwrappedError);
    try {
        maskSensitiveInformation.accept(e);
    } catch (Exception mpe) {
        e = mpe;
    }

    int errorCode = 5000;
    HttpResponseStatus httpStatus = HttpResponseStatus.INTERNAL_SERVER_ERROR;
    if (e instanceof CrateException) {
        CrateException crateException = (CrateException) e;
        if (e instanceof ValidationException) {
            errorCode = 4000 + crateException.errorCode();
            httpStatus = HttpResponseStatus.BAD_REQUEST;
        } else if (e instanceof UnauthorizedException) {
            errorCode = 4010 + crateException.errorCode();
            httpStatus = HttpResponseStatus.UNAUTHORIZED;
        } else if (e instanceof ReadOnlyException) {
            errorCode = 4030 + crateException.errorCode();
            httpStatus = HttpResponseStatus.FORBIDDEN;
        } else if (e instanceof ResourceUnknownException) {
            errorCode = 4040 + crateException.errorCode();
            httpStatus = HttpResponseStatus.NOT_FOUND;
        } else if (e instanceof ConflictException) {
            errorCode = 4090 + crateException.errorCode();
            httpStatus = HttpResponseStatus.CONFLICT;
        } else if (e instanceof UnhandledServerException) {
            errorCode = 5000 + crateException.errorCode();
        }
    } else if (e instanceof ParsingException) {
        errorCode = 4000;
        httpStatus = HttpResponseStatus.BAD_REQUEST;
    } else if (e instanceof MapperParsingException) {
        errorCode = 4000;
        httpStatus = HttpResponseStatus.BAD_REQUEST;
    }

    String message = e.getMessage();
    if (message == null) {
        if (e instanceof CrateException && e.getCause() != null) {
            e = e.getCause();   // use cause because it contains a more meaningful error in most cases
        }
        StackTraceElement[] stackTraceElements = e.getStackTrace();
        if (stackTraceElements.length > 0) {
            message = String.format(Locale.ENGLISH, "%s in %s", e.getClass().getSimpleName(), stackTraceElements[0]);
        } else {
            message = "Error in " + e.getClass().getSimpleName();
        }
    } else {
        message = e.getClass().getSimpleName() + ": " + message;
    }

    StackTraceElement[] usefulStacktrace =
        e instanceof MissingPrivilegeException ? e.getStackTrace() : unwrappedError.getStackTrace();
    return new SQLActionException(message, errorCode, httpStatus, usefulStacktrace);
}