org.pac4j.core.credentials.Credentials Java Examples

The following examples show how to use org.pac4j.core.credentials.Credentials. 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: 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 #2
Source File: Pac4jAuthenticationSuccessHandler.java    From artifact-listener with Apache License 2.0 6 votes vote down vote up
private ClientAuthenticationToken getAuthenticationTokenWithUserDetails(Authentication authentication) {
	Collection<? extends GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
	ClientAuthenticationToken token = getAuthenticationToken(authentication);
	
	if (token != null) {
		UserDetails userDetails = pac4jUserDetailsService.loadUserDetails(token);
		
		if (userDetails != null) {
			this.userDetailsChecker.check(userDetails);
			authorities = userDetails.getAuthorities();
		}
		ClientAuthenticationToken result =  new ClientAuthenticationToken((Credentials) token.getCredentials(),
				token.getClientName(), token.getUserProfile(), authorities);
		result.setDetails(userDetails);
		return result;
	}
	return null;
}
 
Example #3
Source File: AbstractClientAuthenticationHandler.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Override
protected HandlerResult doAuthentication(final Credential credential) throws GeneralSecurityException, PreventedException {
    final ClientCredential clientCredentials = (ClientCredential) credential;
    logger.debug("clientCredentials : {}", clientCredentials);

    final Credentials credentials = clientCredentials.getCredentials();
    final String clientName = credentials.getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<Credentials, UserProfile> client = this.clients.findClient(clientName);
    logger.debug("client : {}", client);

    // web context
    final ServletExternalContext servletExternalContext = (ServletExternalContext) ExternalContextHolder.getExternalContext();
    final HttpServletRequest request = (HttpServletRequest) servletExternalContext.getNativeRequest();
    final HttpServletResponse response = (HttpServletResponse) servletExternalContext.getNativeResponse();
    final WebContext webContext = new J2EContext(request, response);
    
    // get user profile
    final UserProfile userProfile = client.getUserProfile(credentials, webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null) {
        return createResult(clientCredentials, userProfile);
    }

    throw new FailedLoginException("Provider did not produce a user profile for: " + clientCredentials);
}
 
Example #4
Source File: ClientAuthenticationHandlerTests.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    this.fbClient = new MockFacebookClient();
    final Clients clients = new Clients(CALLBACK_URL, fbClient);
    this.handler = new ClientAuthenticationHandler(clients);
    final Credentials credentials = new OAuthCredentials(null, MockFacebookClient.CLIENT_NAME);
    this.clientCredential = new ClientCredential(credentials);
    ExternalContextHolder.setExternalContext(mock(ServletExternalContext.class));
}
 
Example #5
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 #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();
}