org.pac4j.core.exception.RequiresHttpAction Java Examples

The following examples show how to use org.pac4j.core.exception.RequiresHttpAction. 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: AuthenticationFilterTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRedirectIfClientNameIsSet() throws RequiresHttpAction {
	Session session = mock(Session.class);
	when(session.getId()).thenReturn(UUID.randomUUID().toString());
	Response response = mock(Response.class);
	JaxrsWebContext webContext = mock(JaxrsWebContext.class);
	when(webContext.getResponse()).thenReturn(response);
	doNothing().when(basicClient).redirect(webContext, false, false);
	doReturn(basicClient).when(filter).getClient(webContext);
	doReturn(false).when(filter).isAuthenticated(session);
	doReturn(session).when(filter).getSession(context, true);
	doReturn(webContext).when(filter).getContext(context, session);
	filter.filter(context);
	verify(basicClient).redirect(webContext, false, false);
	verify(webContext, atLeast(1)).setResponseHeader(eq(HttpHeaders.LOCATION), any(String.class));
	verify(webContext).setResponseHeader(HttpHeaders.SET_COOKIE, new NewCookie(AuthenticationFilter.AUTH_COOKIE, session.getId(), "/", null, null, NewCookie.DEFAULT_MAX_AGE, false).toString());
	verify(context).abortWith(response);
}
 
Example #2
Source File: CallbackFilterTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnOkIfClientNameIsSet() throws RequiresHttpAction {
	Session session = mock(Session.class);
	Response response = mock(Response.class);
	JaxrsWebContext webContext = mock(JaxrsWebContext.class);
	when(webContext.getResponse()).thenReturn(response);
	doReturn(session).when(filter).getSession(context, true);
	doReturn(webContext).when(filter).getContext(context, session);
	doReturn(client).when(filter).getClient(session);
	Credentials credentials = mock(Credentials.class);
	HttpProfile profile = mock(HttpProfile.class);
	when(client.getCredentials(webContext)).thenReturn(credentials);
	when(client.getUserProfile(credentials, webContext)).thenReturn(profile);
	filter.filter(context);
	verify(session).addAttribute(AuthenticationFilter.PRINCIPAL, profile);
	verify(session).addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "client1");
	verify(sessionStore).save(session);
	verify(webContext).setResponseStatus(Response.Status.OK.getStatusCode());
	verify(listener).authSuccess(session, profile);
	verify(context).abortWith(response);
}
 
Example #3
Source File: AuthenticationFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
    Session session = getSession(request, true);
       request.setProperty(SESSION, session);
       
	if (isWhiteListed(request)) {
	    logger.debug("Request path {} is in whitelisted set of urls. Skipping authentication", request.getUriInfo());
		return;
	}
	if (isAuthenticated(session)) {
	    logger.debug("Session is already authenticated. Skipping authentication");
		return;
	}

	JaxrsWebContext context = getContext(request, session);
	Client client = getClient(context);

	if (client != null) {
		session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName());
		getConfiguration().getSessionStore().save(session);
		
		try {
			client.redirect(context, false, false);
		} catch (RequiresHttpAction e) {
			logger.error("Failed while redirecting the request", e);
			context.setResponseStatus(e.getCode());
		}
	} else {
		context.setResponseStatus(Response.Status.UNAUTHORIZED.getStatusCode());
	}
	context.setResponseHeader(HttpHeaders.SET_COOKIE, createSessionCookie(session).toString());
	request.abortWith(context.getResponse());
}
 
Example #4
Source File: CallbackFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Override
public void filter(ContainerRequestContext request) {
	URI uri = URI.create(getClients().getCallbackUrl());
	if (! HttpUtil.structureUrl(request.getUriInfo().getPath()).equalsIgnoreCase(uri.getPath())) {
	    logger.debug("Request path {} doesn't match callback url. Skipping", request.getUriInfo().getPath());
		return;
	}
	
	Session session = getSession(request, true);
	JaxrsWebContext context = getContext(request, session);
	Client client = getClient(session);
	if (client == null) {
	    client = getClient(context);
	}
	if (client == null) {
		context.setResponseStatus(422);
		if (listener != null) {
		    listener.authFailed(session);
		}
	} else {
		try {
			Credentials credentials = client.getCredentials(context);
			UserProfile userProfile = client.getUserProfile(credentials, context);
			session.addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, client.getName());
			session.addAttribute(PRINCIPAL, userProfile);
			if (listener != null) {
                listener.authSuccess(session, userProfile);
			}
			getConfiguration().getSessionStore().save(session);
			context.setResponseStatus(Response.Status.OK.getStatusCode());
		} catch (RequiresHttpAction e) {
			context.setResponseStatus(e.getCode());
			if (listener != null) {
                listener.authFailed(session);
            }
		}
	}
	request.abortWith(context.getResponse());
}
 
Example #5
Source File: AuthenticationFilterTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetClientNameParamInSessionIfNotAuthenticated() throws RequiresHttpAction {
	Session session = mock(Session.class);
	Response response = mock(Response.class);
	JaxrsWebContext webContext = mock(JaxrsWebContext.class);
	when(webContext.getResponse()).thenReturn(response);
	doReturn(basicClient).when(filter).getClient(webContext);
	doReturn(false).when(filter).isAuthenticated(session);
	doReturn(session).when(filter).getSession(context, true);
	doReturn(webContext).when(filter).getContext(context, session);
	filter.filter(context);
	verify(session).addAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER, "client1");
	verify(sessionStore).save(session);
}
 
Example #6
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();
}
 
Example #7
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();
}