Search in sources :

Example 1 with UnauthorizedException

use of io.quarkus.security.UnauthorizedException in project quarkus-resteasy-problem by TietoEVRY.

the class UnauthorizedExceptionMapperTest method shouldProduceHttp401.

@Test
void shouldProduceHttp401() {
    UnauthorizedException exception = new UnauthorizedException();
    Response response = mapper.toResponse(exception);
    assertThat(response.getStatus()).isEqualTo(401);
}
Also used : Response(javax.ws.rs.core.Response) UnauthorizedException(io.quarkus.security.UnauthorizedException) Test(org.junit.jupiter.api.Test)

Example 2 with UnauthorizedException

use of io.quarkus.security.UnauthorizedException in project quarkus by quarkusio.

the class PrincipalNameFromParameterSecurityCheck method doApply.

private void doApply(SecurityIdentity identity, Object[] parameters, String className, String methodName) {
    if (index > parameters.length - 1) {
        throw genericNotApplicableException(className, methodName);
    }
    Object parameterValue = parameters[index];
    if (!(parameterValue instanceof String)) {
        throw genericNotApplicableException(className, methodName);
    }
    String parameterValueStr = (String) parameterValue;
    if (identity.isAnonymous()) {
        throw new UnauthorizedException();
    }
    String name = identity.getPrincipal().getName();
    if (checkType == CheckType.EQ) {
        if (!name.equals(parameterValueStr)) {
            throw new ForbiddenException();
        }
    } else if (checkType == CheckType.NEQ) {
        if (name.equals(parameterValueStr)) {
            throw new ForbiddenException();
        }
    }
}
Also used : ForbiddenException(io.quarkus.security.ForbiddenException) UnauthorizedException(io.quarkus.security.UnauthorizedException)

Example 3 with UnauthorizedException

use of io.quarkus.security.UnauthorizedException in project quarkus by quarkusio.

the class UndertowDeploymentRecorder method bootServletContainer.

public DeploymentManager bootServletContainer(RuntimeValue<DeploymentInfo> info, BeanContainer beanContainer, LaunchMode launchMode, ShutdownContext shutdownContext) {
    if (info.getValue().getExceptionHandler() == null) {
        // if a 500 error page has not been mapped we change the default to our more modern one, with a UID in the
        // log. If this is not production we also include the stack trace
        boolean alreadyMapped = false;
        for (ErrorPage i : info.getValue().getErrorPages()) {
            if (i.getErrorCode() != null && i.getErrorCode() == StatusCodes.INTERNAL_SERVER_ERROR) {
                alreadyMapped = true;
                break;
            }
        }
        if (!alreadyMapped || launchMode.isDevOrTest()) {
            info.getValue().setExceptionHandler(new QuarkusExceptionHandler());
            info.getValue().addErrorPage(new ErrorPage("/@QuarkusError", StatusCodes.INTERNAL_SERVER_ERROR));
            info.getValue().addServlet(new ServletInfo("@QuarkusError", QuarkusErrorServlet.class).addMapping("/@QuarkusError").setAsyncSupported(true).addInitParam(QuarkusErrorServlet.SHOW_STACK, Boolean.toString(launchMode.isDevOrTest())));
        }
    }
    setupRequestScope(info.getValue(), beanContainer);
    try {
        ClassIntrospecter defaultVal = info.getValue().getClassIntrospecter();
        info.getValue().setClassIntrospecter(new ClassIntrospecter() {

            @Override
            public <T> InstanceFactory<T> createInstanceFactory(Class<T> clazz) throws NoSuchMethodException {
                BeanContainer.Factory<T> res = beanContainer.instanceFactory(clazz);
                if (res == null) {
                    return defaultVal.createInstanceFactory(clazz);
                }
                return new InstanceFactory<T>() {

                    @Override
                    public InstanceHandle<T> createInstance() throws InstantiationException {
                        BeanContainer.Instance<T> ih = res.create();
                        return new InstanceHandle<T>() {

                            @Override
                            public T getInstance() {
                                return ih.get();
                            }

                            @Override
                            public void release() {
                                ih.close();
                            }
                        };
                    }
                };
            }
        });
        ExceptionHandler existing = info.getValue().getExceptionHandler();
        info.getValue().setExceptionHandler(new ExceptionHandler() {

            @Override
            public boolean handleThrowable(HttpServerExchange exchange, ServletRequest request, ServletResponse response, Throwable throwable) {
                if (throwable instanceof AuthenticationFailedException || throwable instanceof UnauthorizedException) {
                    String location = servletContext.getDeployment().getErrorPages().getErrorLocation(throwable);
                    // if these have been mapped we use the mapping
                    if (location == null || location.equals("/@QuarkusError")) {
                        if (throwable instanceof AuthenticationFailedException || exchange.getSecurityContext().getAuthenticatedAccount() == null) {
                            if (!exchange.isResponseStarted()) {
                                exchange.getSecurityContext().setAuthenticationRequired();
                                if (exchange.getSecurityContext().authenticate()) {
                                    // if we can authenticate then the request is just forbidden
                                    // this can happen with lazy auth
                                    exchange.setStatusCode(StatusCodes.FORBIDDEN);
                                }
                            }
                        } else {
                            exchange.setStatusCode(StatusCodes.FORBIDDEN);
                        }
                        return true;
                    }
                } else if (throwable instanceof ForbiddenException) {
                    String location = servletContext.getDeployment().getErrorPages().getErrorLocation(throwable);
                    // if these have been mapped we use the mapping
                    if (location == null || location.equals("/@QuarkusError")) {
                        exchange.setStatusCode(StatusCodes.FORBIDDEN);
                        return true;
                    }
                }
                return existing.handleThrowable(exchange, request, response, throwable);
            }
        });
        ServletContainer servletContainer = Servlets.defaultContainer();
        DeploymentManager manager = servletContainer.addDeployment(info.getValue());
        manager.deploy();
        manager.start();
        servletContext = manager.getDeployment().getServletContext();
        shutdownContext.addShutdownTask(new Runnable() {

            @Override
            public void run() {
                servletContext = null;
            }
        });
        return manager;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ServletRequest(javax.servlet.ServletRequest) ErrorPage(io.undertow.servlet.api.ErrorPage) Instance(javax.enterprise.inject.Instance) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) DeploymentManager(io.undertow.servlet.api.DeploymentManager) ImmediateAuthenticationMechanismFactory(io.undertow.util.ImmediateAuthenticationMechanismFactory) InstanceFactory(io.undertow.servlet.api.InstanceFactory) ServletInfo(io.undertow.servlet.api.ServletInfo) ExceptionHandler(io.undertow.servlet.api.ExceptionHandler) HttpServerExchange(io.undertow.server.HttpServerExchange) UnauthorizedException(io.quarkus.security.UnauthorizedException) ServletResponse(javax.servlet.ServletResponse) ForbiddenException(io.quarkus.security.ForbiddenException) ClassIntrospecter(io.undertow.servlet.api.ClassIntrospecter) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ForbiddenException(io.quarkus.security.ForbiddenException) UnauthorizedException(io.quarkus.security.UnauthorizedException) InstanceFactory(io.undertow.servlet.api.InstanceFactory) ServletContainer(io.undertow.servlet.api.ServletContainer) InstanceHandle(io.undertow.servlet.api.InstanceHandle)

Example 4 with UnauthorizedException

use of io.quarkus.security.UnauthorizedException in project quarkus by quarkusio.

the class QuarkusErrorHandler method handle.

@Override
public void handle(RoutingContext event) {
    try {
        if (event.failure() == null) {
            event.response().setStatusCode(event.statusCode());
            event.response().end();
            return;
        }
        // this can happen if there is no auth mechanisms
        if (event.failure() instanceof UnauthorizedException) {
            HttpAuthenticator authenticator = event.get(HttpAuthenticator.class.getName());
            if (authenticator != null) {
                authenticator.sendChallenge(event).subscribe().with(new Consumer<Boolean>() {

                    @Override
                    public void accept(Boolean aBoolean) {
                        event.response().end();
                    }
                }, new Consumer<Throwable>() {

                    @Override
                    public void accept(Throwable throwable) {
                        event.fail(throwable);
                    }
                });
            } else {
                event.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end();
            }
            return;
        }
        if (event.failure() instanceof ForbiddenException) {
            event.response().setStatusCode(HttpResponseStatus.FORBIDDEN.code()).end();
            return;
        }
        if (event.failure() instanceof AuthenticationFailedException) {
            // generally this should be handled elsewhere
            // but if we get to this point bad things have happened
            // so it is better to send a response than to hang
            event.response().setStatusCode(HttpResponseStatus.UNAUTHORIZED.code()).end();
            return;
        }
    } catch (IllegalStateException e) {
        // ignore this if the response is already started
        if (!event.response().ended()) {
            // could be that just the head is committed
            event.response().end();
        }
        return;
    }
    if (!event.response().headWritten()) {
        event.response().setStatusCode(event.statusCode() > 0 ? event.statusCode() : 500);
    }
    String uuid = BASE_ID + ERROR_COUNT.incrementAndGet();
    String details;
    String stack = "";
    Throwable exception = event.failure();
    String responseContentType = null;
    try {
        responseContentType = ContentTypes.pickFirstSupportedAndAcceptedContentType(event);
    } catch (RuntimeException e) {
        // Let's shield ourselves from bugs in this parsing code:
        // we're already handling an exception,
        // so the priority is to return *something* to the user.
        // If we can't pick the appropriate content-type, well, so be it.
        exception.addSuppressed(e);
    }
    if (showStack && exception != null) {
        details = generateHeaderMessage(exception, uuid);
        stack = generateStackTrace(exception);
    } else {
        details = generateHeaderMessage(uuid);
    }
    if (event.failure() instanceof IOException) {
        log.debugf(exception, "IOError processing HTTP request to %s failed, the client likely terminated the connection. Error id: %s", event.request().uri(), uuid);
    } else {
        log.errorf(exception, "HTTP Request to %s failed, error id: %s", event.request().uri(), uuid);
    }
    // if not we just return
    if (event.response().ended()) {
        return;
    } else if (event.response().headWritten()) {
        event.response().end();
        return;
    }
    if (responseContentType == null) {
        responseContentType = "";
    }
    switch(responseContentType) {
        case ContentTypes.TEXT_HTML:
        case ContentTypes.APPLICATION_XHTML:
        case ContentTypes.APPLICATION_XML:
        case ContentTypes.TEXT_XML:
            htmlResponse(event, details, exception);
            break;
        case ContentTypes.APPLICATION_JSON:
        case ContentTypes.TEXT_JSON:
            jsonResponse(event, responseContentType, details, stack);
            break;
        default:
            // We default to JSON representation
            switch(contentTypeDefault.orElse(HttpConfiguration.PayloadHint.JSON)) {
                case HTML:
                    htmlResponse(event, details, exception);
                    break;
                case JSON:
                default:
                    jsonResponse(event, ContentTypes.APPLICATION_JSON, details, stack);
                    break;
            }
            break;
    }
}
Also used : ForbiddenException(io.quarkus.security.ForbiddenException) AuthenticationFailedException(io.quarkus.security.AuthenticationFailedException) HttpAuthenticator(io.quarkus.vertx.http.runtime.security.HttpAuthenticator) IOException(java.io.IOException) UnauthorizedException(io.quarkus.security.UnauthorizedException)

Example 5 with UnauthorizedException

use of io.quarkus.security.UnauthorizedException in project quarkus-test-suite by quarkus-qe.

the class FailureHandler method handler.

public void handler(final RoutingContext ctx) {
    JsonObject error = defaultError(ctx.normalisedPath());
    if (ctx.failure() instanceof NotFoundException) {
        NotFoundException notFoundExp = (NotFoundException) ctx.failure();
        error.put("status", notFoundExp.getHttpErrorCode()).put("error", HttpResponseStatus.valueOf(notFoundExp.getHttpErrorCode()).reasonPhrase());
        ctx.response().setStatusCode(notFoundExp.getHttpErrorCode());
    }
    if (ctx.failure() instanceof HttpException) {
        HttpException httpExp = (HttpException) ctx.failure();
        error.put("status", httpExp.getStatusCode());
    }
    if (ctx.failure() instanceof UnauthorizedException) {
        error.put("status", HttpResponseStatus.UNAUTHORIZED.code());
        error.put("error", HttpResponseStatus.valueOf(HttpResponseStatus.UNAUTHORIZED.code()).reasonPhrase());
    }
    if (ctx.failure().getMessage() != null) {
        error.put("message", ctx.failure().getMessage());
    }
    ctx.response().setStatusCode(error.getInteger("status"));
    ctx.response().end(error.encode());
}
Also used : UnauthorizedException(io.quarkus.security.UnauthorizedException) JsonObject(io.vertx.core.json.JsonObject) HttpException(io.vertx.ext.web.handler.HttpException)

Aggregations

UnauthorizedException (io.quarkus.security.UnauthorizedException)15 Transactional (javax.transaction.Transactional)8 ForbiddenException (io.quarkus.security.ForbiddenException)3 CreateSetDTO (de.dofusdu.dto.CreateSetDTO)2 SetDTO (de.dofusdu.dto.SetDTO)2 Equipment (de.dofusdu.entity.Equipment)2 Resource (de.dofusdu.entity.Resource)2 Set (de.dofusdu.entity.Set)2 Weapon (de.dofusdu.entity.Weapon)2 AuthenticationFailedException (io.quarkus.security.AuthenticationFailedException)2 IOException (java.io.IOException)2 CreateRecipePositionDTO (de.dofusdu.dto.CreateRecipePositionDTO)1 Consumable (de.dofusdu.entity.Consumable)1 Item (de.dofusdu.entity.Item)1 Pet (de.dofusdu.entity.Pet)1 RecipePosition (de.dofusdu.entity.RecipePosition)1 StatusBuilder (io.fabric8.kubernetes.api.model.StatusBuilder)1 UnauthorizedExceptionMapper (io.quarkus.resteasy.runtime.UnauthorizedExceptionMapper)1 HttpAuthenticator (io.quarkus.vertx.http.runtime.security.HttpAuthenticator)1 AdmissionResponse (io.stackgres.operatorframework.admissionwebhook.AdmissionResponse)1