Skip to content

Get the authenticated user profiles

LELEU Jérôme edited this page Oct 16, 2018 · 8 revisions

1) Retrieve the user profile(s) thanks to the web context and ProfileManager

You can get the profile of the authenticated user using profileManager.get(true) (false not to use the session, but only the current HTTP request). You can test if the user is authenticated using profileManager.isAuthenticated(). You can get all the profiles of the authenticated user (if ever multiple ones are kept) using profileManager.getAll(true).

Example:

WebContext context = new J2EContext(request, response);
ProfileManager manager = new ProfileManager(context);
Optional<CommonProfile> profile = manager.get(true);

The retrieved profile is at least a CommonProfile, from which you can retrieve the most common attributes 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:

FacebookProfile facebookProfile = (FacebookProfile) commonProfile;

2) Retrieve the user profiles using the WebSecurityHelper or the RestSecurityHelper

First, you must register the helpers components:

@ComponentScan(basePackages = "org.pac4j.springframework.helper")

or

@Import(HelperConfig.class)

Then, for a web application, you can inject the WebSecurityHelper:

@Autowired
private WebSecurityHelper webSecurityHelper;

or for a REST API, you can inject the RestSecurityHelper:

@Autowired
private RestSecurityHelper restSecurityHelper;

With the injected helper, you can get the user profile(s) (as well as the J2EContext and ProfileManager):

@Autowired
private WebSecurityHelper webSecurityHelper;

@RequestMapping("/index.html")
public String index(final Map<String, Object> map) throws HttpAction {
   map.put("profiles", webSecurityHelper.getProfiles());
   final J2EContext context = webSecurityHelper.getJ2EContext();
   map.put("sessionId", context.getSessionStore().getOrCreateSessionId(context));
   return "index";
}

Clone this wiki locally