org.pac4j.core.exception.TechnicalException Java Examples

The following examples show how to use org.pac4j.core.exception.TechnicalException. 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 File: ClientActionTests.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
@Test
public void checkUnautorizedProtocol() throws Exception {
    final MockHttpServletRequest mockRequest = new MockHttpServletRequest();
    mockRequest.setParameter(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "BasicAuthClient");

    final ServletExternalContext servletExternalContext = mock(ServletExternalContext.class);
    when(servletExternalContext.getNativeRequest()).thenReturn(mockRequest);

    final MockRequestContext mockRequestContext = new MockRequestContext();
    mockRequestContext.setExternalContext(servletExternalContext);

    final BasicAuthClient basicAuthClient = new BasicAuthClient();
    final Clients clients = new Clients(MY_LOGIN_URL, basicAuthClient);
    final ClientAction action = new ClientAction(mock(CentralAuthenticationService.class), clients);

    try {
        action.execute(mockRequestContext);
        fail("Should fail as the HTTP protocol is not authorized");
    } catch (final TechnicalException e) {
        assertEquals("Only CAS, OAuth, OpenID and SAML protocols are supported: " + basicAuthClient, e.getMessage());
    }
}
 
Example #2
Source File: JaxRsContext.java    From jax-rs-pac4j with Apache License 2.0 6 votes vote down vote up
private MultivaluedMap<String, String> extractedParameters() {
    if (parameters == null) {
        MultivaluedHashMap<String, String> multivaluedHashMap = new MultivaluedHashMap<>();
        // efficient
        multivaluedHashMap.putAll(requestContext.getUriInfo().getQueryParameters());
        parameters = multivaluedHashMap;
        if (MediaType.APPLICATION_FORM_URLENCODED_TYPE.isCompatible(requestContext.getMediaType())) {
            readAndResetEntityStream(stream -> {
                try {
                    Form form = providers.getMessageBodyReader(Form.class, Form.class, new Annotation[0],
                            MediaType.APPLICATION_FORM_URLENCODED_TYPE).readFrom(Form.class, Form.class,
                                    new Annotation[0], MediaType.APPLICATION_FORM_URLENCODED_TYPE,
                                    requestContext.getHeaders(), stream);
                    form.asMap().forEach(parameters::addAll);
                    return null;
                } catch (IOException e) {
                    throw new TechnicalException(e);
                }
            });
        }
    }
    return parameters;
}
 
Example #3
Source File: JaxRsContext.java    From jax-rs-pac4j with Apache License 2.0 6 votes vote down vote up
private <T> T readAndResetEntityStream(Function<InputStream, T> f) {
    try (InputStream entityStream = requestContext.getEntityStream()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = entityStream.read(buffer)) > -1) {
            baos.write(buffer, 0, len);
        }
        baos.flush();
        ByteArrayInputStream stream = new ByteArrayInputStream(baos.toByteArray());
        try {
            return f.apply(stream);
        } finally {
            stream.reset();
            requestContext.setEntityStream(stream);
        }
    } catch (IOException e) {
        throw new TechnicalException(e);
    }
}
 
Example #4
Source File: VertxSessionStore.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<SessionStore<VertxWebContext>> buildFromTrackableSession(final VertxWebContext context, final Object trackableSession) {
    if (trackableSession != null) {
        final CompletableFuture<io.vertx.ext.web.Session> vertxSessionFuture = new CompletableFuture<>();
        sessionStore.get((String) trackableSession, asyncResult -> {
            if (asyncResult.succeeded()) {
                vertxSessionFuture.complete(asyncResult.result());
            } else {
                vertxSessionFuture.completeExceptionally(asyncResult.cause());
            }
        });
        final CompletableFuture<VertxSessionStore> pac4jSessionFuture = vertxSessionFuture.thenApply(session -> {
            if (session != null) {
                return new VertxSessionStore(sessionStore, session);
            } else {
                return null;
            }
        });
        try {
            return Optional.ofNullable(pac4jSessionFuture.get());
        } catch (final InterruptedException|ExecutionException e) {
            throw new TechnicalException(e);
        }
    }
    return Optional.empty();
}
 
Example #5
Source File: KnoxSessionStore.java    From knox with Apache License 2.0 6 votes vote down vote up
private String compressEncryptBase64(final Object o) {
    if (o == null || o.equals("")
        || (o instanceof Map<?,?> && ((Map<?,?>)o).isEmpty())) {
        return null;
    } else {
        byte[] bytes = javaSerializationHelper.serializeToBytes((Serializable) o);

        /* compress the data  */
        try {
            bytes = compress(bytes);

            if(bytes.length > 3000) {
                logger.warn("Cookie too big, it might not be properly set");
            }

        } catch (final IOException e) {
            throw new TechnicalException(e);
        }

        EncryptionResult result = cryptoService.encryptForCluster(this.clusterName, PAC4J_PASSWORD, bytes);
        return Base64.encodeBase64String(result.toByteAray());
    }
}
 
Example #6
Source File: LogoutHandler.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(final RoutingContext routingContext) {

    final LogoutLogic<Void, VertxWebContext> bestLogic = FindBest.logoutLogic(null, config, DefaultLogoutLogic.INSTANCE);
    final HttpActionAdapter<Void, VertxWebContext> bestAdapter = FindBest.httpActionAdapter(null, config, VertxHttpActionAdapter.INSTANCE);

    final VertxWebContext webContext = new VertxWebContext(routingContext, sessionStore);

    vertx.executeBlocking(future -> {
                bestLogic.perform(webContext, config, bestAdapter, defaultUrl, logoutUrlPattern, localLogout, destroySession, centralLogout);
                future.complete(null);
            },
            false,
            asyncResult -> {
                // If we succeeded we're all good here, the job is done either through approving, or redirect, or
                // forbidding
                // However, if an error occurred we need to handle this here
                if (asyncResult.failed()) {
                    routingContext.fail(new TechnicalException(asyncResult.cause()));
                }
            });

}
 
Example #7
Source File: CallbackHandler.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(RoutingContext event) {

    final CallbackLogic<Void, VertxWebContext> bestLogic = FindBest.callbackLogic(null, config, DefaultCallbackLogic.INSTANCE);
    final HttpActionAdapter<Void, VertxWebContext> bestAdapter = FindBest.httpActionAdapter(null, config, VertxHttpActionAdapter.INSTANCE);

    // Can we complete the authentication process here?
    final VertxWebContext webContext = new VertxWebContext(event, sessionStore);

    vertx.executeBlocking(future -> {
        bestLogic.perform(webContext, config, bestAdapter, defaultUrl, saveInSession, multiProfile, renewSession, defaultClient);
        future.complete(null);
    },
    false,
    asyncResult -> {
        // If we succeeded we're all good here, the job is done either through approving, or redirect, or
        // forbidding
        // However, if an error occurred we need to handle this here
        if (asyncResult.failed()) {
            event.fail(new TechnicalException(asyncResult.cause()));
        }
    });

}
 
Example #8
Source File: KnoxSessionStore.java    From knox with Apache License 2.0 6 votes vote down vote up
private Serializable uncompressDecryptBase64(final String v) {
    if (v != null && !v.isEmpty()) {
        byte[] bytes = Base64.decodeBase64(v);
        EncryptionResult result = EncryptionResult.fromByteArray(bytes);
        byte[] clear = cryptoService.decryptForCluster(this.clusterName,
            PAC4J_PASSWORD,
            result.cipher,
            result.iv,
            result.salt);
        if (clear != null) {
            try {
                return javaSerializationHelper.unserializeFromBytes(unCompress(clear));
            } catch (IOException e) {
                throw new TechnicalException(e);
            }
        }
    }
    return null;
}
 
Example #9
Source File: DefaultJsonConverter.java    From vertx-pac4j with Apache License 2.0 6 votes vote down vote up
@Override
public Object encodeObject(Object value) {
    if (value == null) {
        return null;
    } else if (isPrimitiveType(value)) {
        return value;
    } else if (value instanceof Object[]) {
        Object[] src = ((Object[]) value);
        List<Object> list = new ArrayList<>(src.length);
        fillEncodedList(src, list);
        return new JsonArray(list);
    } else {
        try {
            return new JsonObject().put("class", value.getClass().getName()).put("value",
                    new JsonObject(encode(value)));
        } catch (Exception e) {
            throw new TechnicalException("Error while encoding object", e);
        }
    }
}
 
Example #10
Source File: Pac4jExceptionFilter.java    From artifact-listener with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
		ServletException {
	try {
		chain.doFilter(request, response);
	} catch (final TechnicalException e) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		httpRequest.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, e);
		getRedirectStrategy().sendRedirect(httpRequest, httpResponse, Pac4jAuthenticationUtils.LOGIN_FAILURE_URL);
	}
}
 
Example #11
Source File: AuthenticationFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected Client getClient(JaxrsWebContext context) {
    try {
        return clients.findClient(context);
    } catch (TechnicalException e) {
        logger.debug("Error while getting the client from the context", e);
        return null;
    }
}
 
Example #12
Source File: FilterHelper.java    From jee-pac4j with Apache License 2.0 5 votes vote down vote up
/**
 * Add a filter mapping.
 *
 * @param name the name fo the filter
 * @param filter the filter
 * @param parameters the URLs on which it applies and the supported dispatcher types
 */
public void addFilterMapping(final String name, final Filter filter, final Object... parameters) {
    assertNotBlank("name", name);
    assertNotNull("filter", filter);
    assertNotNull("parameters", parameters);

    final List<String> urls = new ArrayList<>();
    final List<DispatcherType> types = new ArrayList<>();
    for (final Object parameter : parameters) {
        if (parameter instanceof String) {
            urls.add((String) parameter);
        } else if (parameter instanceof DispatcherType) {
            types.add((DispatcherType) parameter);
        } else {
            throw new TechnicalException("Unsupported parameter type: " + parameter);
        }
    }
    if (urls.isEmpty()) {
        throw new TechnicalException("No URL mapping defined for filter: " + name);
    }
    if (types.isEmpty()) {
        types.add(DispatcherType.REQUEST);
    }

    final FilterRegistration.Dynamic registration = servletContext.addFilter(name, filter);
    registration.addMappingForUrlPatterns(EnumSet.copyOf(types), true, urls.toArray(new String[urls.size()]));
}
 
Example #13
Source File: VertxClusteredMapStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
public void voidAsyncOpToBlocking(Func1<AsyncMap, Observable> asyncOp) {
    CompletableFuture<Void> future = new CompletableFuture<>();

    rxVertx.sharedData().getClusterWideMapObservable(PAC4J_SHARED_DATA_KEY)
            .map(asyncOp)
            .subscribe(result -> future.complete(null));

    try {
        future.get(blockingTimeoutSeconds, TimeUnit.SECONDS);
    } catch (InterruptedException|ExecutionException |TimeoutException e) {
        throw new TechnicalException(e);
    }
}
 
Example #14
Source File: VertxClusteredMapStore.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<V> get(K key) {
    voidAsyncOpToBlocking(map -> map.getObservable((key)));

    final CompletableFuture<V> valueFuture = new CompletableFuture<>();
    rxVertx.sharedData().<K, V>getClusterWideMapObservable(PAC4J_SHARED_DATA_KEY)
            .flatMap(map -> map.getObservable(key))
            .subscribe(valueFuture::complete);
    try {
        return Optional.ofNullable(valueFuture.get(blockingTimeoutSeconds, TimeUnit.SECONDS));
    } catch (InterruptedException|ExecutionException|TimeoutException e) {
        throw new TechnicalException(e);
    }
}
 
Example #15
Source File: DefaultJsonConverter.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
private Object decode(JsonObject src) {
    try {
        return decode(src.getJsonObject("value").encode(), Class.forName(src.getString("class")));
    } catch (Exception e) {
        throw new TechnicalException("Error while decoding object", e);
    }
}
 
Example #16
Source File: VertxHttpActionAdapter.java    From vertx-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public Void adapt(final HttpAction action, final VertxWebContext context) {
    if (action != null) {
        final RoutingContext routingContext = context.getVertxRoutingContext();
        int code = action.getCode();
        LOG.debug("Adapting action: {}", code);

        if (code < 400) {
            routingContext.response().setStatusCode(code);
        } else {
            routingContext.fail(code);
        }

        if (action instanceof WithLocationAction) {
            final WithLocationAction withLocationAction = (WithLocationAction) action;
            context.setResponseHeader(HttpConstants.LOCATION_HEADER, withLocationAction.getLocation());
            routingContext.response().end();

        } else if (action instanceof WithContentAction) {
            final WithContentAction withContentAction = (WithContentAction) action;
            final String content = withContentAction.getContent();

            if (content != null) {
                routingContext.response().setChunked(true);
                routingContext.response().write(content);
                routingContext.response().end();
            }
        }
        return null;
    }

    throw new TechnicalException("No action provided");
}
 
Example #17
Source File: SecurityHandler.java    From vertx-pac4j with Apache License 2.0 4 votes vote down vote up
protected final TechnicalException toTechnicalException(final Throwable t) {
    return (t instanceof TechnicalException) ? (TechnicalException) t : new TechnicalException(t);
}
 
Example #18
Source File: ProvidersContext.java    From jax-rs-pac4j with Apache License 2.0 4 votes vote down vote up
public <A> A resolveNotNull(Class<A> clazz) {
    return resolve(clazz).orElseThrow(() -> new TechnicalException(clazz.getName() + " cannot be null"));
}
 
Example #19
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    //final String clientName = request.getParameter(this.clients.getClientNameParameter());
    final String clientName = request.getParameter("state");
    //logger.debug("clientName : {}", clientName);
    logger.info("clientName : {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.info("client : {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        logger.info("mechanism == " + mechanism.name());
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.info("credentials : {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.info("requires http action : {}", e);
            response.flushBuffer();
            ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.info("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            logger.info("credentials is not null : {}", credentials);
            WebUtils.putTicketGrantingTicketInRequestScope(context,
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials)));
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}
 
Example #20
Source File: AuthenticationFilterTest.java    From minnal with Apache License 2.0 4 votes vote down vote up
@Test(expectedExceptions=TechnicalException.class)
public void shouldThrowExceptionIfClientNameIsNotFoundInSession() {
	Session session = mock(Session.class);
	when(session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER)).thenReturn("unknownClient");
	filter.getClient(session);
}
 
Example #21
Source File: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
protected Event doExecute(final RequestContext context) throws Exception {
    final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
    final HttpServletResponse response = WebUtils.getHttpServletResponse(context);
    final HttpSession session = request.getSession();

    // web context
    final WebContext webContext = new J2EContext(request, response);

    // get client
    final String clientName = request.getParameter(this.clients.getClientNameParameter());
    logger.debug("clientName: {}", clientName);

    // it's an authentication
    if (StringUtils.isNotBlank(clientName)) {
        // get client
        final BaseClient<Credentials, CommonProfile> client =
                (BaseClient<Credentials, CommonProfile>) this.clients
                .findClient(clientName);
        logger.debug("client: {}", client);

        // Only supported protocols
        final Mechanism mechanism = client.getMechanism();
        if (!SUPPORTED_PROTOCOLS.contains(mechanism)) {
            throw new TechnicalException("Only CAS, OAuth, OpenID and SAML protocols are supported: " + client);
        }

        // get credentials
        final Credentials credentials;
        try {
            credentials = client.getCredentials(webContext);
            logger.debug("credentials: {}", credentials);
        } catch (final RequiresHttpAction e) {
            logger.debug("requires http action: {}", e);
            response.flushBuffer();
            final ExternalContext externalContext = ExternalContextHolder.getExternalContext();
            externalContext.recordResponseComplete();
            return new Event(this, "stop");
        }

        // retrieve parameters from web session
        final Service service = (Service) session.getAttribute(SERVICE);
        context.getFlowScope().put(SERVICE, service);
        logger.debug("retrieve service: {}", service);
        if (service != null) {
            request.setAttribute(SERVICE, service.getId());
        }
        restoreRequestAttribute(request, session, THEME);
        restoreRequestAttribute(request, session, LOCALE);
        restoreRequestAttribute(request, session, METHOD);

        // credentials not null -> try to authenticate
        if (credentials != null) {
            final TicketGrantingTicket tgt = 
                    this.centralAuthenticationService.createTicketGrantingTicket(new ClientCredential(credentials));
            WebUtils.putTicketGrantingTicketInScopes(context, tgt);
            return success();
        }
    }

    // no or aborted authentication : go to login page
    prepareForLoginPage(context);
    return error();
}