This article is a follow-up to Implementing SAML in Java.

We have a Java application built with spring security and spring security SAML. SAML provides authentication and security for web resources, ie. web pages and content in our website. What if the application also has some REST APIs?

Authenticating REST APIs in SAML application

REST APIs primarily use HTTP methods and do not have a web page serving them. An application that has its web resources authenticated through SAML does not differentiate between web resource URLs and REST APIs.

As a result, when the REST URLs are accessed, the user is prompted with SAML login page in response, which asks for his credentials in Html.

Separating REST APIs from SAML

REST APIs should be able to bypass SAML authentication and should be authenticated using username/password or OAuth or any REST authentication mechanism (SAML is not suited for REST).

Separation of REST APIs from SAML URLs can be done with the help of Spring security configuration. To achieve this, the URLs that serve APIs should adhere to a pattern, like starting with ‘api/’ or ‘rest/’. Through configuration, we can now segregate REST to go through a rest authentication entry point and the rest through Samlentrypoint as default.

Login API

If using OAuth for rest login, we need to expose a login API that does not need authentication and returns back a token that can be further used in other rest APIs for authentication.

Rest authentication entry point

The commence method of the RestAuthenticationEntryPoint is called when the web API request does not come with expected authentication. For a REST web service, we should be able to authenticate only by a request to the correct URI and if the user is not authenticated all requests should simply fail with a 401 UNAUTHORIZED status code.

REST Authentication

The REST login can be designed to give the user a token (a JWT constructed from login response) and further REST requests can be intercepted by a filter that validates the token and sets spring security authentication in the security context. If the token is invalid, a security exception is thrown and handled by RestAuthenticatioEnrtyPoint which promptly sends 401(Unauthorized) back to the user.