Issue
- When making calls to a REST API service created with RestBuilder that includes the Authorization Bearer token header, the responses often return a 401 Unauthorized status. However, when the same service is tested using Swagger within a Liferay session, it responds with a 200 OK.
Resolution
If you are using an external token validation mechanism (not relying on a Liferay OAuth application), you need to make some actions:
-
-
Add the com.liferay.oauth2.provider.rest.internal.security.auth.verifier.OAuth2RESTAuthVerifier component to the blacklist.
-
Implement your own token validation logic by creating a custom AuthVerifier. You can refer to the attached SampleAuthVerifier.java for guidance on implementation.
-
If you want to allow guest users to consume the service, you must include the following properties in the @Component annotation of the RestServicesApplication class generated by RestBuilder
- Enabling Guest User Access to REST Services:
"liferay.access.control.disable=true",
"auth.verifier.guest.allowed=true",
"oauth2.scopechecker.type=none"
Additional Information
SampleAuthVerifier.java:
import com.liferay.portal.kernel.security.auth.AccessControlContext;
import com.liferay.portal.kernel.security.auth.verifier.AuthVerifier;
import com.liferay.portal.kernel.security.auth.verifier.AuthVerifierResult;
import java.util.Properties;
import org.osgi.service.component.annotations.Component;
@Component(
property = {
"auth.verifier.SampleAuthVerifier.urls.includes=*"
},
service = AuthVerifier.class
)
public class SampleAuthVerifier implements AuthVerifier {
public String getAuthType() {
return SampleAuthVerifier.class.getName();
}
@Override
public AuthVerifierResult verify(
AccessControlContext accessControlContext, Properties properties) {
AuthVerifierResult authVerifierResult = new AuthVerifierResult();
// NOT_APPLICABLE
// authVerifierResult.setState(AuthVerifierResult.State.NOT_APPLICABLE);
// SUCCESS
// authVerifierResult.setState(AuthVerifierResult.State.SUCCESS);
// authVerifierResult.setUserId(20122);//Useradmin
// ERROR
// authVerifierResult.setState(AuthVerifierResult.State.SC_UNAUTHORIZED);
// authVerifierResult.setState(AuthVerifierResult.State.INVALID_CREDENTIALS);
return authVerifierResult;
}
}