Secure Your Play 2 Webapp With play-pac4j in 5 Minutes

DZone 's Guide to

Secure Your Play 2 Webapp With play-pac4j in 5 Minutes

The full security library play-pac4j v2.0 for any Play 2 web application is available now.

· Web Dev Zone ·
Free Resource

I'm proud to announce the release of play-pac4j v2.0 (https://github.com/pac4j/play-pac4j) based on pac4j v1.8 (https://github.com/pac4j/pac4j) for any Play 2 web application. It's now a full security library, easy and powerful, which supports authentication and authorization, but also application logout and advanced features like CSRF protection.

It supports most authentication mechanisms: OAuth (Facebook, Twitter, Google, Yahoo...), CAS, HTTP (form, basic auth...), OpenID, SAML, Google App Engine, OpenID Connect, JWT, LDAP, RDBMS, MongoDB and Stormpath and authorization checks (role / permission, CSRF token...)

In four easy steps, secure your webapp:

1) add the dependencies on the library (play-pac4j-java for Java Play app or play-pac4j-scala_2.11 for Scala app) and on the required authentication mechanisms (the pac4j-oauth library for Facebook for example)

2) define the authentication mechanisms (clients) and authorizers (to check authorizations) in a module. For example: Facebook authentication and ROLE_ADMIN

public class SecurityModule extends AbstractModule {

    protected void configure() {
        FacebookClient facebookClient = new FacebookClient("xx", "yy");
        Clients clients = new Clients("http://localhost:9000/callback", facebookClient);
        Config config = new Config(clients);
        config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));

3) Define the callback controller for Facebook authentication (routes):

GET      /callback      org.pac4j.play.CallbackController.callback()
POST     /callback      org.pac4j.play.CallbackController.callback()

4) Secure the /facebook/index.html url to require the user to be authenticated and perform a Facebook authentication if he is not:

GET    /facebook/index.html       controllers.Application.facebookIndex()
public class Application extends UserProfileController<CommonProfile> {

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

and/or requires the user to have the ROLE_ADMIN:

@RequiresAuthentication(clientName = "FacebookClient", authorizerName = "admin")

Read the documentation: https://github.com/pac4j/play-pac4j and try the demo in Java: https://github.com/pac4j/play-pac4j-java-demo or in Scala: https://github.com/pac4j/play-pac4j-scala-demo

play 2.0, security

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}