Coder Social home page Coder Social logo

jamhall / play-pac4j Goto Github PK

View Code? Open in Web Editor NEW

This project forked from msven/play-pac4j

0.0 3.0 0.0 147 KB

Java and Scala multi protocols (CAS, OAuth, OpenID, HTTP...) client for Play 2.x framework (based on pac4j)

Home Page: www.pac4j.org

License: Apache License 2.0

Java 76.11% Scala 23.89%

play-pac4j's Introduction

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 2.0pac4j-oauthGoogle2ClientGoogle2Profile
LinkedInOAuth 1.0 & 2.0pac4j-oauthLinkedInClient & LinkedIn2ClientLinkedInProfile & LinkedIn2Profile
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
GoogleOpenIDpac4j-openidGoogleOpenIdClientGoogleOpenIdProfile

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.

Learn more by browsing the play-pac4j Javadoc and the pac4j Javadoc.

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.
val appDependencies = Seq(
    "org.pac4j" % "pac4j-http" % "1.4.2-SNAPSHOT",
    "org.pac4j" % "pac4j-cas" % "1.4.2-SNAPSHOT",
    "org.pac4j" % "pac4j-openid" % "1.4.2-SNAPSHOT",
    "org.pac4j" % "pac4j-oauth" % "1.4.2-SNAPSHOT"
)

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("http://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("http://localhost:9000/casProxyCallback");
  casClient.setCasProxyReceptor(casProxyReceptor);*/
  casClient.setCasLoginUrl("http://localhost:8080/cas/login");
  // OpenID
  final MyOpenIdClient myOpenIdClient = new MyOpenIdClient();
        
  final Clients clients = new Clients("http://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.2-SNAPSHOT is under development. It's available on the Sonatype snapshots repository as a Maven dependency :

The latest release of the play-pac4j project is the 1.1.1 version :

<dependency>
    <groupId>org.pac4j</groupId>
    <artifactId>play-pac4j_java</artifactId> or <artifactId>play-pac4j_scala2.9</artifactId> or <artifactId>play-pac4j_scala2.10</artifactId>
    <version>1.1.1</version>
</dependency>

See the release notes.

Contact

If you have any question, please use the following mailing lists :

play-pac4j's People

Contributors

leleuj avatar rhudson avatar msven avatar

Watchers

Jamie Hall avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.