Nicolas Raoul
Nicolas Raoul

Reputation: 60203

Fixing "PrincipalException: PermissionChecker not initialized" the Liferay 7 way

With Liferay 6, using *LocalServiceUtil static calls was common. Starting from Liferay 7, these calls should be avoided in favor of @Referenceing the OSGi service and using it as a private member of the class, if I understood correctly (feel free to correct me).

Problem: When I replace my old *LocalServiceUtil calls with the OSGi-friendly equivalent, I get this exception:

com.liferay.portal.kernel.security.auth.PrincipalException:
    PermissionChecker not initialized
        at com.liferay.portal.kernel.service.BaseServiceImpl.getPermissionChecker
        at com.liferay.portal.service.impl.UserServiceImpl.getUserById

How to fix it?

I could get a random admin via the OSGi equivalent of UserLocalServiceUtil.getRoleUsers(RoleLocalServiceUtil.getRole(company.getCompanyId(),"Administrator").getRoleId()) and use it in the the OSGi equivalent of PermissionThreadLocal.setPermissionChecker(PermissionCheckerFactoryUtil.create(randomAdmin)) but that sounds very hacky, plus it would put the responsibility of my code's actions on the shoulders of this unlucky admin.

My code:

protected void myMethod() {
    userService.getUserById(userId);
}

@Reference(unbind = "-")
protected com.liferay.portal.kernel.service.UserService userService;

Upvotes: 1

Views: 1205

Answers (1)

Miroslav Ligas
Miroslav Ligas

Reputation: 1307

I think you actually wanted to inject UserLocalService.

In OSGi you should only strip the *Util suffix to receive equivalent functionality.

What you did is moved from LocalService (UserLocalServiceUtil) to remote service (UserService). The local services do not check permissions so there is no permission checker initialisation.

Apart from the above, you should be sure that no mischief can happen when using Local services. It's not recommended to expose this kind of functionality to end users but it's fine for some background processing.

Upvotes: 1

Related Questions