Get the authenticated user profiles - pac4j/play-pac4j GitHub Wiki

1) ProfileManager

You can get the profile of the authenticated user using the ProfileManager.

>> Read the documentation of the ProfileManager component.

Examples:

In Java:

public class Application {

    @Inject
    protected SessionStore playSessionStore;

    public Result getUserProfile() {
        PlayWebContext webContext = new PlayWebContext(ctx())
        ProfileManager profileManager = new ProfileManager(webContext, playSessionStore);
        Optional profile = profileManager.getProfile();
        ....
    }

}

In Scala:

class Application @Inject()(playSessionStore: SessionStore, val controllerComponents: ControllerComponents) extends Controller {

    def getUserProfile() = Action { request =>
        val webContext = new PlayWebContext(request)
        val profileManager = new ProfileManager(webContext, playSessionStore)
        val profile = profileManager.getProfile()
        ....
    }
}

2) Get the user profile within a twirl template (scala)

To retrive the current profile/profiles or ProfileManager within a twirl template you can inject the: Pac4jScalaTemplateHelper in to your controller or template.

First you have to register the Pac4jScalaTemplateHelper in your SecurityModule like this:

bind(classOf[Pac4jScalaTemplateHelper[CommonProfile]])

Than in your Controller inject the Pac4jScalaTemplateHelper as an implicit:

class ApplicationWithScalaHelper @Inject()(implicit val pac4jTemplateHelper: Pac4jScalaTemplateHelper[CommonProfile] ...

In your action you must define the request as an implicit:

def userView = Secure("FormClient") { implicit request =>
  Ok(views.html.index())
}

And finally in your template you can use the Pac4jScalaTemplateHelper to access the current profile:

@import org.pac4j.play.scala.Pac4jScalaTemplateHelper
@import org.pac4j.core.profile.CommonProfile
@(title: String)(implicit pac4jScalaTemplateHelper: Pac4jScalaTemplateHelper[CommonProfile], requestHeader: RequestHeader)

<h1>@title</h1>

@if(pac4jScalaTemplateHelper.getCurrentProfile.isDefined) {
  <h2>Hello user: @pac4jScalaTemplateHelper.getCurrentProfile.get.getUsername</h2>
}
⚠️ **GitHub.com Fallback** ⚠️