Expired sessions and unauthorized HTTP requests

Current version: 9.0

Your application must redirect users to the login page when their session is expired. SPEAK 3 does this by handling the 401 Unauthorized Access error for all HTTP requests within your application.

You must use Sitecore routing and hosting conventions for single page applications to handle authorization for the application entry point.

The authorization handling flow is:

  1. The client sends a request to the server.

  2. The server verifies if the request is authenticated:

    • If true, the server proceeds with the request.

    • If not, the server returns a 401 error to the client.

  3. The client handles the response:

    • If authenticated, it proceeds as normal

    • If the 401 error returns, it refreshes the page. The server redirects to the login on the page refresh (if that entry-point checks for authorization).

Backend setup

If you develop backend API services using the ASP.NET Web API, use the [Authorize] attribute to enable authentication for a service. If you develop using MVC, use the [SitecoreAuthorize] attribute instead as this handles the session correctly for MVC.

Handle the 401 error code for all HTTP requests

The SPEAK3.Integration package for Angular (ng-sc) provides an application-wide solution to check for 401 error codes in Angular applications.

Import this module in your code to automatically patch the official Angular HTTP class to catch all 401 errors. When a 401 error is returned to your application, the module triggers a page reload. Sitecore then redirects the user to the login page when the page is refreshed:

RequestResponse
import { SciAuthHttpModule } from '@speak/ng-sc/auth-http';
// add module in root app module
@NgModule({
 imports: [
   SciAuthHttpModule,
 ]
})

Continue to use the official HTTP module for your requests. There is no difference in how you write your code, except that the code handles all 401 requests for you. Your application must still handle other error codes, such as a 404 error.

Do you have some feedback for us?

If you have suggestions for improving this article,