org.pac4j.core.client.Client Java Examples

The following examples show how to use org.pac4j.core.client.Client. 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: ClientAction.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    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);

    // save parameters in web session
    final WebApplicationService service = WebUtils.getService(context);
    logger.debug("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.debug("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #2
Source File: ClientAction.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
/**
 * Prepare the data for the login page.
 *
 * @param context The current webflow context
 */
protected void prepareForLoginPage(final RequestContext context) {
    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);

    // save parameters in web session
    final Service service = (Service) context.getFlowScope().get(SERVICE);
    logger.info("save service: {}", service);
    session.setAttribute(SERVICE, service);
    saveRequestParameter(request, session, THEME);
    saveRequestParameter(request, session, LOCALE);
    saveRequestParameter(request, session, METHOD);

    // for all clients, generate redirection urls
    for (final Client client : this.clients.findAllClients()) {
        final String key = client.getName() + "Url";
        final BaseClient baseClient = (BaseClient) client;
        final String redirectionUrl = baseClient.getRedirectionUrl(webContext);
        logger.info("{} -> {}", key, redirectionUrl);
        context.getFlowScope().put(key, redirectionUrl);
    }
}
 
Example #3
Source File: CallbackFilterTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setup() {
	client = mock(Client.class);
	listener = mock(AuthenticationListener.class);
	when(client.getName()).thenReturn("client1");
	clients = new Clients("/callback", client);
	sessionStore = mock(SessionStore.class);
	configuration = mock(SecurityConfiguration.class);
	when(configuration.getSessionStore()).thenReturn(sessionStore);
	filter = spy(new CallbackFilter(clients, configuration));
	filter.registerListener(listener);
	context = mock(ContainerRequestContext.class);
	uriInfo = mock(UriInfo.class);
	when(uriInfo.getPath()).thenReturn("/callback");
	when(context.getUriInfo()).thenReturn(uriInfo);
}
 
Example #4
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void clients() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clients.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(2);

    Client client = config.getClients().getClients().get(0);
    assertThat(client).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("basic");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNull();
}
 
Example #5
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void allOptionsClients() throws Exception {
    Pac4jFactory conf = getPac4jFactory("alloptions-pac4j.yaml");
    Config config = conf.build();

    assertThat(config).isExactlyInstanceOf(FakeConfig.class);
    final FakeConfig fakeConfig = (FakeConfig) config;
    assertThat(fakeConfig.getProperties().size()).isEqualTo(2);
    assertThat(config.getClients().getClients()).hasSize(2);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    assertThat(config.getAuthorizers().size()).isEqualTo(1);

    assertThat(config.getMatchers().size()).isEqualTo(1);
}
 
Example #6
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void clientsAndProperties() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clientsandproperties-pac4j.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(2);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    Client client1 = config.getClients().getClients().get(1);
    assertThat(client1).isInstanceOf(DirectBasicAuthClient.class);
    assertThat(client1.getName()).isEqualTo("DirectBasicAuthClient");
    assertThat(((DirectBasicAuthClient) client1).getAuthenticator())
            .isNotNull()
            .isInstanceOf(SimpleTestUsernamePasswordAuthenticator.class);

    assertThat(config.getAuthorizers().size()).isEqualTo(0);

    assertThat(config.getMatchers().size()).isEqualTo(0);
}
 
Example #7
Source File: AuthenticationFilter.java    From minnal with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("rawtypes")
protected User retrieveProfile(Session session) {
	Object profile = session.getAttribute(PRINCIPAL);
	if (profile == null) {
		return null;
	}
	Client client = getClient(session);
	Class<UserProfile> type = Generics.getTypeParameter(client.getClass(), UserProfile.class);
	if (type.isAssignableFrom(profile.getClass())) {
		return new User((UserProfile) profile);
	}
	if (profile instanceof Map) {
		String buffer = Serializer.DEFAULT_JSON_SERIALIZER.serialize(profile);
		profile = Serializer.DEFAULT_JSON_SERIALIZER.deserialize(buffer, type);
		User user = new User((UserProfile) profile);
		session.addAttribute(PRINCIPAL, profile);
		return user;
	}
	// Can't come here 
	return null;
}
 
Example #8
Source File: BundleFactoryTest.java    From dropwizard-pac4j with Apache License 2.0 6 votes vote down vote up
@Test
public void emptyPac4jInConfig() {
    setup(App.class, "empty-pac4j.yaml");

    App app = dropwizardTestSupport.getApplication();
    ObjectMapper om = dropwizardTestSupport.getObjectMapper();
    Environment env = dropwizardTestSupport.getEnvironment();

    Config config = app.bundle.getConfig();
    assertThat(config).isNotNull();
    // this is the default url resolver!
    assertThat(config.getClients().getUrlResolver())
            .isInstanceOf(JaxRsUrlResolver.class);
    assertThat(om.findMixInClassFor(Client.class)).isNotNull();
    assertThat(env.jersey().getResourceConfig().getSingletons())
            .haveAtLeastOne(CONDSI);

    assertThat(env.getApplicationContext().getSessionHandler())
            .isInstanceOf(SessionHandler.class);
}
 
Example #9
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 #10
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 #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: AuthenticationFilter.java    From minnal with Apache License 2.0 5 votes vote down vote up
protected Client getClient(Session session) {
    String clientName = session.getAttribute(Clients.DEFAULT_CLIENT_NAME_PARAMETER);
    if (Strings.isNullOrEmpty(clientName)) {
        return null;
    }
    return clients.findClient(clientName);
}
 
Example #13
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 #14
Source File: SyncopeWASAML2ClientCustomizer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(final Client client) {
    if (client instanceof SAML2Client) {
        LOG.debug("Customizing SAML2 client {}", client.getName());
        final SAML2Client saml2Client = (SAML2Client) client;
        SAML2Configuration configuration = saml2Client.getConfiguration();
        configuration.setKeystoreGenerator(new SyncopeWASAML2ClientKeystoreGenerator(restClient, saml2Client));
        configuration.setMetadataGenerator(new SyncopeWASAML2ClientMetadataGenerator(restClient, saml2Client));
    }
}
 
Example #15
Source File: Pac4jClientConfigurationDecoratorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void decorateClients(List<Client> clients, Map<String, String> properties) {
  clients.forEach(client -> {
    tested.incrementAndGet();
    if (decorate) {
      decorated.incrementAndGet();
    }
  });
}
 
Example #16
Source File: Pac4jClientConfigurationDecoratorTest.java    From knox with Apache License 2.0 5 votes vote down vote up
@Test
public void testClientConfigDecoration() throws Exception {
  final AtomicInteger tested = new AtomicInteger(0);
  final AtomicInteger decorated = new AtomicInteger(0);

  final ClientConfigurationDecorator passiveDecorator = new TestClientConfigurationDecorator(tested, decorated, false);
  final ClientConfigurationDecorator activeDecorator = new TestClientConfigurationDecorator(tested, decorated, true);
  final Pac4jClientConfigurationDecorator pac4jConfigurationDecorator = new Pac4jClientConfigurationDecorator(Arrays.asList(passiveDecorator, activeDecorator));
  final Client client = EasyMock.createNiceMock(Client.class);
  pac4jConfigurationDecorator.decorateClients(Collections.singletonList(client), null);
  assertEquals(2, tested.get());
  assertEquals(1, decorated.get());
}
 
Example #17
Source File: SAML2ClientConfigurationDecorator.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void decorateClients(List<Client> clients, Map<String, String> properties) {
  for (Client client : clients) {
    if (SAML2_CLIENT_CLASS_NAME.equalsIgnoreCase(client.getName())) {
      final SAML2Client saml2Client = (SAML2Client) client;
      setUseNameQualifierFlag(properties, saml2Client);
      setForceAuthFlag(properties, saml2Client);
      setPassiveFlag(properties, saml2Client);
      setNameIdPolicyFormat(properties, saml2Client);
    }
  }
}
 
Example #18
Source File: AzureADClientConfigurationDecorator.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
public void decorateClients(List<Client> clients, Map<String, String> properties) {
  for (Client client : clients) {
    if (AZURE_AD_CLIENT_CLASS_NAME.equalsIgnoreCase(client.getName())) {
      // special handling for Azure AD, use path separators instead of query params
      ((AzureAdClient) client).setCallbackUrlResolver(new PathParameterCallbackUrlResolver());
    }
  }
}
 
Example #19
Source File: BundleFactoryTest.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void noPac4jInConfig() {
    setup(App.class, "no-pac4j.yaml");

    App app = dropwizardTestSupport.getApplication();
    ObjectMapper om = dropwizardTestSupport.getObjectMapper();
    Environment env = dropwizardTestSupport.getEnvironment();

    assertThat(app.bundle.getConfig()).isNull();
    // if one use the bundle with null pac4j, one will get the mixing
    // registered anyway
    assertThat(om.findMixInClassFor(Client.class)).isNotNull();
    assertThat(env.jersey().getResourceConfig().getSingletons())
            .doesNotHave(CONDSI);
}
 
Example #20
Source File: DefaultConfigurationTest.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Test
public void clientsProperties() throws Exception {
    Pac4jFactory conf = getPac4jFactory("clientsproperties-pac4j.yaml");
    Config config = conf.build();

    assertThat(config.getClients().getClients()).hasSize(1);

    Client client0 = config.getClients().getClients().get(0);
    assertThat(client0).isExactlyInstanceOf(FacebookClient.class);
    assertThat(((FacebookClient) client0).getKey()).isEqualTo("fbId");

    assertThat(config.getAuthorizers().size()).isEqualTo(1);

    assertThat(config.getMatchers().size()).isEqualTo(0);
}
 
Example #21
Source File: DefaultFeatureSupport.java    From dropwizard-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Bootstrap<?> bootstrap) {
    ObjectMapper om = bootstrap.getObjectMapper();

    // for Config
    om.addMixIn(SessionStore.class, sessionStoreMixin());
    om.addMixIn(Authorizer.class, authorizerMixin());
    om.addMixIn(HttpActionAdapter.class, httpActionAdapterMixin());
    om.addMixIn(Matcher.class, matcherMixin());
    om.addMixIn(SecurityLogic.class, securityLogicMixin());
    om.addMixIn(CallbackLogic.class, callbackLogicMixin());
    om.addMixIn(LogoutLogic.class, logoutLogicMixin());

    // for Clients
    om.addMixIn(Client.class, clientMixin());
    om.addMixIn(BaseClient.class, baseClientMixin());

    // for Clients and Client subsclasses
    om.addMixIn(AjaxRequestResolver.class, ajaxRequestResolverMixin());
    om.addMixIn(UrlResolver.class, urlResolverMixin());
    om.addMixIn(CallbackUrlResolver.class, callbackUrlResolverMixin());
    om.addMixIn(AuthorizationGenerator.class,
            authorizationGeneratorMixin());

    // for Client/BaseClient
    om.addMixIn(Authenticator.class, authenticatorMixin());
    om.addMixIn(CredentialsExtractor.class, credentialExtractorMixin());
    om.addMixIn(ProfileCreator.class, profileCreatorMixin());

    // for IndirectClient
    om.addMixIn(RedirectActionBuilder.class, redirectActionBuilderMixin());
    om.addMixIn(LogoutActionBuilder.class, logoutActionBuilderMixin());
    
    // for some of the Authenticators
    om.addMixIn(PasswordEncoder.class, passwordEncoderMixin());
}
 
Example #22
Source File: ClientAuthenticationHandler.java    From cas4.0.x-server-wechat with Apache License 2.0 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 String clientName = clientCredentials.getCredentials().getClientName();
    logger.debug("clientName : {}", clientName);

    // get client
    final Client<org.pac4j.core.credentials.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(clientCredentials.getCredentials(), webContext);
    logger.debug("userProfile : {}", userProfile);

    if (userProfile != null && StringUtils.isNotBlank(userProfile.getTypedId())) {
        clientCredentials.setUserProfile(userProfile);
        return new HandlerResult(
                this,
                new BasicCredentialMetaData(credential),
                new SimplePrincipal(userProfile.getTypedId(), userProfile.getAttributes()));
    }

    throw new FailedLoginException("Provider did not produce profile for " + clientCredentials);
}
 
Example #23
Source File: Pac4jClientConfigurationDecorator.java    From knox with Apache License 2.0 4 votes vote down vote up
@Override
public void decorateClients(List<Client> clients, Map<String, String> properties) {
  decorators.forEach(decorator -> decorator.decorateClients(clients, properties));
}
 
Example #24
Source File: SyncopeWAConfiguration.java    From syncope with Apache License 2.0 4 votes vote down vote up
@Autowired
@Bean
public DelegatedClientFactoryCustomizer<Client> delegatedClientCustomizer(final WARestClient restClient) {
    return new SyncopeWASAML2ClientCustomizer(restClient);
}
 
Example #25
Source File: Pac4jFactory.java    From dropwizard-pac4j with Apache License 2.0 4 votes vote down vote up
@JsonProperty
public void setClients(List<Client> clients) {
    this.clients = clients;
}
 
Example #26
Source File: Pac4jFactory.java    From dropwizard-pac4j with Apache License 2.0 4 votes vote down vote up
@JsonProperty
public List<Client> getClients() {
    return clients;
}
 
Example #27
Source File: SecurityPlugin.java    From minnal with Apache License 2.0 4 votes vote down vote up
/**
 * @param callbackUrl
 * @param clients
 */
public SecurityPlugin(String callbackUrl, AuthenticationListener listener, Client... clients) {
    this.clients = new Clients(callbackUrl, clients);
    this.listener = listener;
}
 
Example #28
Source File: ClientConfigurationDecorator.java    From knox with Apache License 2.0 2 votes vote down vote up
/**
 * Decorates the given clients' configuration using the given properties (if applicable)
 *
 * @param clients
 *          the client, whose configuration should be decorated
 * @param properties
 *          the properties which may contain the required information to decorate the clients
 */
void decorateClients(List<Client> clients, Map<String, String> properties);
 
Example #29
Source File: SecurityPlugin.java    From minnal with Apache License 2.0 2 votes vote down vote up
/**
 * @param callbackUrl
 * @param clients
 */
public SecurityPlugin(String callbackUrl, Client... clients) {
	this.clients = new Clients(callbackUrl, clients);
}