Search code examples
c#asp.net-identityasp.net-core-webapiasp.net-core-3.0

Using Identity.UI in WebAPI project


I'm pretty new to Asp.NET and would like some more information on how to proceed. I have a standard WebAPI project which contains the standard weather template - I'm trying to apply some authentication via registering/logging in. I know theres a way to have template do it for you when create project, but for web api it doesn't let you do a local database which I want.

So right now I've attached the Identity.UI package to give me access to this method and generate the migration for identity tables

 services.AddDefaultIdentity<IdentityUser>()
   .AddEntityFrameworkStores<ApplicationDbContext>();

which allows me to use the UserManager to register a user and for login I do this:

    if (!ModelState.IsValid) return BadRequest();

    var result = await m_userManager.FindByNameAsync(user.Email);
    var correct = await m_userManager.CheckPasswordAsync(result, user.Password);

    if (!correct) return BadRequest();

    return Ok(new { token = m_tokenService.BuildToken(user.Email) });

My question is a correct way of handling registering and login via WebAPI because the Microsoft.AspNetCore.Identity.UI package as the name suggests provides razor pages for login/registering which I don't really need which makes me believe this isn't correct. Is there downside/problem doing it this way, or is this a cleaner way of doing this.


Solution

  • The default Microsoft.AspNetCore.Identity.UI package provides a razor page for login/registration that seems redundant for web api .

    For implementing Microsoft identity on web api to handle basic individual user accounts , you could try to use JWT tokens , refer to the following links which are good tutorials about using JwtBearer Authentication in an ASP.NET Core API Project :

    https://wildermuth.com/2018/04/10/Using-JwtBearer-Authentication-in-an-API-only-ASP-NET-Core-Project

    https://dotnetdetail.net/asp-net-core-3-0-web-api-token-based-authentication-example-using-jwt-in-vs2019/