Search code examples
asp.netasp.net-coreasp.net-identity

Storing user data with ASP.NET 5.0 without OpenID Connect and Razor pages


In ASP.NET 5.0 I would like to implement a simple cookie authentication and store the user data safely in the database.

The cookie authentication works fine, this way I am able to implement on the frontend side all the user-related functionality in the SPA so there are no navigations outside the Angular app. (This way there is no redirection to an external Razor page to implement for example the login functionality.)

However, I have now the problem of storing safely user data on the server-side. (For example, hashing the password correctly.) If I would use ASP.NET Identity, it would solve all the storing issues out of the box. The problem is, that all the examples show only implementations with Razor pages and OIDC.

Is there a possibility to use the ASP.NET Idenitity only for storing the user data without using the Razor pages and OIDC?

I don't want to use the embedded OIDC implementation of ASP.NET, because I have a tiny Angular SPA, and all the redirections from/to the Razor pages of Identity make the user experience bad. On the other hand, if I would use the Razor pages of Identity I would need to style them to the same as my Angular application, which seems to be a smelly code duplication to me. (Among others I also would need to apply the material design on them.)


Solution

  • The answer is yes, there is a possibility for this!

    First of all Identity should be added to the services following way:

    services.AddIdentity<ApplicationUser, IdentityRole>(options => options.Stores.MaxLengthForKeys = 128)
            .AddEntityFrameworkStores<ApplicationDbContext>();
    

    Note that not AddDefaultIdentity is used, because AddDefaultIdentity involves the default Razor pages as well, in my case I don't want to have them.

    This way the UserManager is available and it can be injected in the constructor and it can be used for creating users in the DB. (The UserManager handles the safe storage of user data.)

    However, this way when there was an unauthorized or a forbidden API call, the backend tried to redirect to some default routes that did not exist. So following configuration needed to be added as well:

    services.ConfigureApplicationCookie(options =>
    {
        options.Events.OnRedirectToLogin = (context) =>
        {
           context.Response.StatusCode = 401;
           return Task.CompletedTask;
        };
        options.Events.OnRedirectToAccessDenied = (context) =>
        {
            context.Response.StatusCode = 403;
            return Task.CompletedTask;
        };
    });
    

    Using the above approach services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(..) needed to be removed.