Skip to content

retech/pac4j

 
 

Repository files navigation

What is pac4j ?

pac4j is a Profile & Authentication Client for Java (it's a global rebuilding of the scribe-up library). It targets all the protocols supporting the following mechanism :

  1. From the client application, redirect the user to the "provider" for authentication (HTTP 302)
  2. After successful authentication, redirect back the user from the "provider" to the client application (HTTP 302) and get the user credentials
  3. With these credentials, get the profile of the authenticated user (direct call from the client application to the "provider").

It has a very simple and unified API to support these 4 protocols on client side :

  1. OAuth (1.0 & 2.0)
  2. CAS (1.0, 2.0, SAML, logout & proxy)
  3. HTTP (form & basic auth authentications)
  4. OpenID.

It's available under the Apache 2 license.

Technical description

This Maven project is composed of 6 modules :

  1. pac4j-core : this is the core module of the project with the core classes/interfaces :
    • the Client interface is the main API of the project as it defines the mechanism that all clients must follow : getRedirectionUrl(WebContext), getCredentials(WebContext) and getUserProfile(Credentials)
    • the Credentials class is the base class for all credentials
    • the UserProfile class is the base class for all user profiles (it is associated with attributes definition and converters)
    • the CommonProfile class inherits from the UserProfile class and implements all the common getters that profiles must have (getFirstName(), getEmail()...)
    • the WebContext interface represents a web context which can be implemented in a J2E or another environment.

  2. pac4j-oauth : this module is dedicated to OAuth client support, it's the successor of the scribe-up library :
    • the FacebookClient, TwitterClient... classes are the clients for all the providers : Facebook, Twitter...
    • the OAuthCredentials class is the credentials for OAuth support
    • the FacebookProfile, TwitterProfile... classes are the associated profiles, returned by the clients.

    This module is based on the pac4j-core module, the scribe-java library for OAuth protocol support, the Jackson library for JSON parsing and the commons-lang3 library.

  3. pac4j-cas : this module is dedicated to CAS client support :
    • the CasClient class is the client for CAS server (the CasProxyReceptor is dedicated to CAS proxy support)
    • the CasCredentials class is the credentials for CAS support
    • the CasProfile class is the user profile returned by the CasClient.

    This module is based on the pac4j-core module and the Jasig CAS client.

  4. pac4j-http : this module is dedicated to HTTP protocol support :
    • the FormClient & BasicAuthClient classes are the client for form and basic auth authentications
    • the UsernamePasswordCredentials class is the username/password credentials in HTTP support
    • the HttpProfile class is the user profile returned by the FormClient and BasicAuthClient.

    This module is based on the pac4j-core module and the commons-codec library.

  5. pac4j-openid : this module is dedicated to OpenID protocol support :
    • the MyOpenIdClient class is dedicated to MyOpenId
    • the OpenIdCredentials class is the credentials for OpenID support
    • the MyOpenIdProfile class is the user profile for MyOpenId.

    This module is based on the pac4j-core module and the openid4java library.

  6. pac4j-test-cas : this module is made to test CAS support in pac4j.

Learn more by browsing the Javadoc.

Providers supported

ProviderProtocolMaven dependencyClient classProfile class
CAS serverCASpac4j-casCasClient & CasProxyReceptorCasProfile
CAS server using OAuth WrapperOAuth 2.0pac4j-oauthCasOAuthWrapperClientCasOAuthWrapperProfile
DropBoxOAuth 1.0pac4j-oauthDropBoxClientDropBoxProfile
FacebookOAuth 2.0pac4j-oauthFacebookClientFacebookProfile
GitHubOAuth 2.0pac4j-oauthGitHubClientGitHubProfile
GoogleOAuth 2.0pac4j-oauthGoogle2ClientGoogle2Profile
LinkedInOAuth 1.0pac4j-oauthLinkedInClientLinkedInProfile
TwitterOAuth 1.0pac4j-oauthTwitterClientTwitterProfile
Windows LiveOAuth 2.0pac4j-oauthWindowsLiveClientWindowsLiveProfile
WordPressOAuth 2.0pac4j-oauthWordPressClientWordPressProfile
YahooOAuth 1.0pac4j-oauthYahooClientYahooProfile
Web sites with basic auth authenticationHTTPpac4j-httpBasicAuthClientHttpProfile
Web sites with form authenticationHTTPpac4j-httpFormClientHttpProfile
MyOpenIdOpenIDpac4j-openidMyOpenIdClientMyOpenIdProfile

Code sample

Maven dependencies

First, you have define the right dependency : pac4j-oauth for OAuth support or/and pac4j-cas for CAS support or/and pac4j-http for HTTP support or/and pac4j-openid for OpenID support. For example :

<dependency>
    <groupId>org.pac4j</groupId>
    <artifactId>pac4j-oauth</artifactId>
    <version>1.4.0</version>
</dependency>

As the pac4j snapshots libraries are stored in the Sonatype snapshots repository, this repository may be added in the Maven pom.xml file :

<repository>
			<id>sonatype-nexus-snapshots</id>
			<name>Sonatype Nexus Snapshots</name>
			<url>https://oss.sonatype.org/content/repositories/snapshots</url>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
</repository>

OAuth support

If you want to authenticate and get the user profile from Facebook, you have to use the org.pac4j.oauth.client.FacebookClient :

// declare the client (use default scope and fields)
FacebookClient client = new FacebookClient(MY_KEY, MY_SECRET);
// define the client application callback url
client.setCallbackUrl("http://myserver/myapp/callbackUrl");
// send the user to Facebook for authentication and permissions
response.sendRedirect(client.getRedirectionUrl(new J2EContext(request, response)));

...after successfull authentication, in the client application, on the callback url (for Facebook)...

// get OAuth credentials
OAuthCredentials credentials = client.getCredentials(new J2EContext(request, response)));
// get the facebook profile
FacebookProfile facebookProfile = client.getUserProfile(credentials);
System.out.println("Hello : " + facebookProfile.getDisplayName() + " born the " + facebookProfile.getBirthday());

CAS support

For integrating an application with a CAS server, you should use the org.pac4j.cas.client.CasClient :

// declare the client
CasClient client = new CasClient();
// define the client application callback url
client.setCallbackUrl("http://myserver/myapp/callbackUrl");
// send the user to the CAS server for authentication
response.sendRedirect(client.getRedirectionUrl(new J2EContext(request, response)));

...after successfull authentication, in the client application, on the callback url...

// get CAS credentials
CasCredentials credentials = client.getCredentials(new J2EContext(request, response)));
// get the CAS profile
CasProfile casProfile = client.getUserProfile(credentials);
System.out.println("Hello : " + casProfile.getAttribute("anAttribute"));

For proxy support, the org.pac4j.cas.client.CasProxyReceptor class must be used (on the same or new callback url) and declared with the CasClient class :

casClient.setCasProxyReceptor(new CasProxyReceptor());
// casClient.setAcceptAnyProxy(false);
// casClient.setAllowedProxyChains(proxies);

In this case, the org.pac4j.cas.profile.CasProxyProfile must be used to get proxy tickets for other CAS services :

CasProxyProfile casProxyProfile = (CasProxyProfile) casProfile;
String proxyTicket = casProxyProfile.getProxyTicketFor(anotherCasService);

HTTP support

To use form authentication in a web application, you should use the org.pac4j.http.client.FormClient class :

// declare the client
FormClient client = new FormClient("/myloginurl", new MyUsernamePasswordAuthenticator());
client.setCallbackUrl("http://myserver/myapp/callbackUrl");
// send the user to the form for authentication
response.sendRedirect(client.getRedirectionUrl(new J2EContext(request, response)));

...after successfull authentication...

// get username/password credentials
UsernamePasswordCredentials credentials = client.getCredentials(new J2EContext(request, response)));
// get the HTTP profile
HttpProfile httpProfile = client.getUserProfile(credentials);
System.out.println("Hello : " + httpProfile.getUsername());

To use basic auth authentication in a web application, you should use the org.pac4j.http.client.BasicAuthClient class :

// declare the client
BasicAuthClient client = new BasicAuthClient(new MyUsernamePasswordAuthenticator(), new UsernameProfileCreator());

OpenID support

To use myopenid.com for authentication, you should use the org.pac4j.openid.client.MyOpenIdClient class :

// declare the client
MyOpenIdClient client = new MyOpenIdClient();
client.setCallbackUrl("/callbackUrl");
// send the user to myopenid.com for authentication
// we assume the user identifier is in the "openIdUser" request parameter
response.sendRedirect(client.getRedirectionUrl(new J2EContext(request, response)));

...after successfull authentication...

// get the OpenID credentials
OpenIdCredentials credentials = client.getCredentials(new J2EContext(request, response)));
// get the myOpenID profile
MyOpenIdProfile profile = client.getUserProfile(credentials);
System.out.println("Hello : " + profile.getDisplayName());

Multiple clients

If you use multiple clients, you can use more generic objects. All profiles inherit from the org.pac4j.core.profile.CommonProfile class :

// get credentials
Credentials credentials = client.getCredentials(new J2EContext(request, response)));
// get the common profile
CommonProfile commonProfile = client.getUserProfile(credentials);
System.out.println("Hello : " + commonProfile.getFirstName());

If you want to interact more with the OAuth providers (like Facebook), you can retrieve the access token from the (OAuth) profiles :

OAuthProfile oauthProfile = (OAuthProfile) commonProfile;
String accessToken = oauthProfile.getAccessToken();
// or
String accesstoken = facebookProfile.getAccessToken();

You can also group all clients on a single callback url by using the org.pac4j.core.client.Clients class :

Clients clients = new Clients("http://server/app/callbackUrl", fbClient, casClient, formClient myOpenIdClient);
// on the callback url, retrieve the right client
Client client = clients.findClient(new J2EContext(request, response)));

Error handling

All methods of the clients may throw an unchecked org.pac4j.core.exception.TechnicalException, which could be trapped by an appropriate try/catch. The getCredentials(WebContext) method can throw a checked org.pac4j.core.expception.RequiresHttpAction, exception to require some additionnal HTTP action (redirection, basic auth...)

Libraries built with pac4j

Even if you can use pac4j on its own, this library is used to be integrated with :

  1. the cas-server-support-pac4j module to add multi-protocols client support to the CAS server
  2. the play-pac4j library to add multi-protocols client support to the Play 2.x framework in Java and Scala.
  3. the buji-oauth library to add OAuth client support to the Apache Shiro project
  4. the spring-security-oauth-client library to add OAuth client support to Spring Security.
Integration libraryProtocol(s) supportedBased onDemo webapp
cas-server-support-pac4j 4.0.0OAuth / CAS / OpenIDpac4j 1.4.0cas-pac4-oauth-demo
cas-server-support-oauth 3.5.2OAuthscribe-up 1.2.0cas-oauth-demo-3.5.x
play-pac4j 1.1.0OAuth / CAS / OpenID / HTTPpac4j 1.4.0play-pac4j-java-demo
play-pac4j-scala-demo
buji-oauth 1.1.0OAuthscribe-up 1.3.1buji-oauth-demo
spring-security-oauth-client 1.1.0OAuthscribe-up 1.3.1spring-security-oauth-client-demo

Versions

The current version : 1.4.1-SNAPSHOT is under development, it's available in the Sonatype snapshots repository.

The latest release of the pac4j project is the 1.4.0 version :

<dependency>
    <groupId>org.pac4j</groupId>
    <artifactId>pac4j-core</artifactId>
    <version>1.4.0</version>
</dependency>

Learn more about the different versions.

Testing

pac4j is tested by more than 300 unit, bench and integration tests (authentication processes are completely simulated using the HtmlUnit library). To launch the tests, the nr Maven profile should be used. For example :

mvn clean install -Pnr

Use the js Maven profile for Javadoc and sources generation.

Contact

Find me on LinkedIn or by email : leleuj@gmail.com

About

Profile & Authentication Client in Java for CAS, OAuth, OpenID, HTTP... protocols

Resources

License

Stars

Watchers

Forks

Packages

No packages published