Skip to content

Latest commit

 

History

History
202 lines (162 loc) · 10.9 KB

README.md

File metadata and controls

202 lines (162 loc) · 10.9 KB

What is the play-pac4j library ?

The play-pac4j library is a Java and Scala multi-protocols client for Play framework 2.x.

It supports 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 and based on my pac4j library.

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 1.0 & 2.0pac4j-oauthGoogleProvider & Google2ProviderGoogleProfile & Google2Profile
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

Technical description

This library has just 11 classes :

  1. the Config class gathers all the configuration
  2. the Constants class gathers all the constants
  3. the CallbackController class is used to finish the authentication process and logout the user
  4. the StorageHelper class deals with storing/retrieving data from the cache
  5. the JavaWebContext class is a Java wrapper for the user request, response and session
  6. the JavaController class is the Java controller to retrieve the user profile or the redirection url to start the authentication process
  7. the RequiresAuthentication annotation is to protect an action if the user is not authenticated and starts the authentication process if necessary
  8. the RequiresAuthenticationAction class is the action to check if the user is not authenticated and starts the authentication process if necessary
  9. the ScalaController trait is the Scala controller to retrieve the user profile or the redirection url to start the authentication process
  10. the ScalaWebContext class is a Scala wrapper for the user request, response and session
  11. the PlayLogoutHandler class is dedicated to CAS support to handle CAS logout request.

and is based on the pac4j-* libraries.

How to use it ?

Add the required dependencies

First, the dependency on play-pac4j_java must be defined in the Build.scala file for a Java application :

val appDependencies = Seq(
  "org.pac4j" % "play-pac4j_java" % "1.1.0-SNAPSHOT"
)

Or the play-pac4j_scala2.9 dependency for a Scala application in Play framework 2.0 or the play-pac4j_scala2.10 dependency for a Scala application in Play framework 2.1.

As it's a snapshot only available in the Sonatype Snapshots repository, the appropriate resolver must also be defined in the Build.scala file :

val main = PlayProject(appName, appVersion, appDependencies, mainLang = SCALA).settings(
  resolvers += "Sonatype snapshots repository" at "https://oss.sonatype.org/content/repositories/snapshots/"
)

If you want to use a specific client support, you need to add the appropriate dependency :

  • for OAuth support, the pac4j-oauth dependency is required
  • for CAS support, the pac4j-cas dependency is required
  • for HTTP support, the pac4j-http dependency is required
  • for OpenID support, the pac4j-openid dependency is required.

Define the supported clients

To use client support, your application must inherit from the JavaController class for a Java application :

public class Application extends JavaController {

or from the ScalaController trait for a Scala application :

object Application extends ScalaController {

You must define all the clients you want to support in the onStart method of your Global class for your Java or Scala application :

public void onStart(final Application app) {
  // OAuth
  final FacebookClient facebookClient = new FacebookClient("fb_key", "fb_secret");
  final TwitterClient twitterClient = new TwitterClient("tw_key", "tw_secret");  
  // HTTP
  final FormClient formClient = new FormClient("https://localhost:9000/theForm", new SimpleTestUsernamePasswordAuthenticator());
  final BasicAuthClient basicAuthClient = new BasicAuthClient(new SimpleTestUsernamePasswordAuthenticator());
  // CAS
  final CasClient casClient = new CasClient();
  // casClient.setLogoutHandler(new PlayLogoutHandler());
  // casClient.setCasProtocol(CasProtocol.SAML);
  // casClient.setGateway(true);
  /*final CasProxyReceptor casProxyReceptor = new CasProxyReceptor();
  casProxyReceptor.setCallbackUrl("https://localhost:9000/casProxyCallback");
  casClient.setCasProxyReceptor(casProxyReceptor);*/
  casClient.setCasLoginUrl("https://localhost:8080/cas/login");
  // OpenID
  final MyOpenIdClient myOpenIdClient = new MyOpenIdClient();
        
  final Clients clients = new Clients("https://localhost:9000/callback", facebookClient, twitterClient, formClient, basicAuthClient, casClient, myOpenIdClient); // , casProxyReceptor);
  Config.setClients(clients);
}

The /callback url is the callback url where the providers (Facebook, Twitter, CAS...) redirects the user after successfull authentication (with the appropriate credentials).

Get user profiles and protect actions

You can get the profile of the (authenticated) user in a Java application by using the getUserProfile() method :

public static Result index() {
  // profile (maybe null if not authenticated)
  final CommonProfile profile = getUserProfile();
  return ok(views.html.index.render(profile));
}

And protect the access of a specific url by using the RequiresAuthentication annotation :

@RequiresAuthentication(clientName = "FacebookClient")
public static Result protectedIndex() {
  // profile
  final CommonProfile profile = getUserProfile();
  return ok(views.html.protectedIndex.render(profile));
}

Or you can get the profile of the (authenticated) user in a Scala application by using the getUserProfile(request) method :

def index = Action { request =>
  val profile = getUserProfile(request)
  Ok(views.html.index(profile))
}

And protect the access of a specific url by using the RequiresAuthentication function :

def protectedIndex = RequiresAuthentication("FacebookClient") { profile =>
 Action { request =>
   Ok(views.html.protectedIndex(profile))
 }
}

After successfull authentication, the originally requested url is restored.

Get redirection urls

You can also explicitely compute a redirection url to a provider for authentication by using the getRedirectionUrl method for a Java application :

public static Result index() {
  final String url = getRedirectionUrl("TwitterClient", "/targetUrl");
  return ok(views.html.index.render(url));
}

Or in a Scala application (always call the getOrCreateSessionId(request) method first) :

def index = Action { request =>
  val newSession = getOrCreateSessionId(request)
  val url = getRedirectionUrl(request, newSession, "FacebookClient", "/targetUrl")
  Ok(views.html.index(url)).withSession(newSession)
}

Define the callback url

The callback url must be defined in the routes file as well as the logout :

GET   /                       controllers.Application.index()
GET   /protected/index.html   controllers.Application.protectedIndex()
GET   /callback               org.pac4j.play.CallbackController.callback()
POST  /callback               org.pac4j.play.CallbackController.callback()
GET   /logout                 org.pac4j.play.CallbackController.logoutAndRedirect()

Use the appropriate profile

From the CommonProfile, you can retrieve the most common properties that all profiles share. But you can also cast the user profile to the appropriate profile according to the provider used for authentication. For example, after a Facebook authentication :

// facebook profile
FacebookProfile facebookProfile = (FacebookProfile) commonProfile;

Or for all the OAuth profiles, to get the access token :

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

Demos

Demos with Facebook, Twitter, CAS, form authentication, basic auth authentication and myopenid.com providers are available at :

Versions

The current version 1.1.0-SNAPSHOT is under development. This is the first version of the play-pac4j project.

The last released version is the play-oauth-client 1.0.0 library (which only supports OAuth) :

<dependency>
    <groupId>com.github.leleuj.play.oauth.client</groupId>
    <artifactId>play-oauth-client</artifactId>
    <version>1.0.0</version>
</dependency>

Contact

Find me on LinkedIn or by email : [email protected]