Doubting using Identity for ASP.NET Core Web API

佐手、 提交于 2019-12-12 03:05:39

问题


I'm working on a Web API and I am not sure if I did a mistake by avoiding using the Identity membership system and implementing my own authentication setup.

From what I've read it looks like it's a great solution for frontend-ish logins such as Facebook where you can use UserManager to easily commit different CRUD's on users, etc but I've also seen it being used by other people for their Web API's.

I didn't avoid it exclusively because of the upper paragraph but for the following excerpt from this official doc.

Identity is enabled for the application by calling UseIdentity in the Configure method of the Startup class. This adds cookie-based authentication to the request pipeline.

This may sound weird but why would I want cookie-based authentication for a Web API ? I've managed to secure it using a custom Login/Claims tables and JWT Bearer Authentication and this is how I've done it.

This is how I've managed to implement the custom User/Claim tables.

UserIdentity table (Downsized version of AspNetUsers tables from the Identity Container)

public class UserIdentity
    {
        public Guid Id { get; set; }
        public string Username { get; set; }
        public string HashPassword { get; set; }
    }

User claims (Downsized version of AspNetUserClaims)

public class UserClaims
    {
        public Guid Id { get; set; }
        public string ClaimType { get; set; }
        public string ClaimValue { get; set; }

        [Required]
        public virtual UserIdentity UserIdentity { get; set; }
    }

This is my DbContext ( note that I've used DbContext instead of IdentityDbContext )

public class CustomContext : DbContext
    {
        public CustomContext(DbContextOptions<CustomContext> options)
            : base(options)
        {
        }

        public DbSet<UserIdentity> Users { get; set; }
        public DbSet<UserClaims> UserClaims { get; set; }
        // other custom DSets...
          ....
    }

And my JWT controller

[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Get([FromForm] ApplicationUser applicationUser)
{
    var identity = await GetClaimsIdentity(applicationUser, _customContext);
    if (identity == null)
    {
        _logger.LogInformation($"Invalid username ({applicationUser.UserName}) or password ({applicationUser.Password})");
        return BadRequest("Invalid credentials");
    }

    var claims = new[]
    {
new Claim(JwtRegisteredClaimNames.Sub, applicationUser.UserName),
new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
new Claim(JwtRegisteredClaimNames.Iat, ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(), ClaimValueTypes.Integer64),
//identity.FindFirst("Diamond")
identity.Claims.Last()
};

And in the GetClaimsIdentity I just get all the user's claims from the passed DbContext instance from the controller's CTOR.

private static Task<ClaimsIdentity> GetClaimsIdentity(ApplicationUser user, CustomContext customContext)
        {
            var currentUser = partnerContext.Users.FirstOrDefault(x => x.HashPassword == user.Password && x.Username == user.UserName);

            if (currentUser != null)
            {
                //Getting the user claims
                var listOfClaims =
                    from claim in partnerContext.UserClaims.Where(x => x.UserIdentity.Id == currentUser.Id)
                    select new Claim(claim.ClaimType, claim.ClaimValue);

                if (!listOfClaims.Any())
                    return Task.FromResult<ClaimsIdentity>(null);

                return Task.FromResult(new ClaimsIdentity(new GenericIdentity(user.UserName, "Token"),
                    listOfClaims));
            }

            return Task.FromResult<ClaimsIdentity>(null);
        }

This approach works but it does make me a little bit confuse whether I've done the right choice for ditching IdentityDbContext just because of the "cookie-based authentication" ability.

I also read about customizing your very own Custom storages, but I end up having the same doubt, why do I need "cookie-authentication", what am I missing ?

来源:https://stackoverflow.com/questions/39862314/doubting-using-identity-for-asp-net-core-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!