ASP.NET 5 Identity user management in Web API

So I'm building an api using asp.net 5 MVC 6, and I followed the Microsoft tutorial on building new web APIs to get started. I then followed the answers to this question to implement JWT token based authentication, but I am stuck here:

if ((req.username == "TEST" && req.password == "TEST") || (req.username == "TEST2" && req.password == "TEST"))
{
    DateTime? expires = DateTime.UtcNow.AddMinutes(2);
    var token = GetToken(req.username, expires);
    return new { authenticated = true, entityId = 1, token = token, tokenExpires = expires };

}

Instead of this if statement I need to somehow call the UserManager class and check if the username and password actually matches a user in my database, as I do in my old MVC 5 API with:

ApplicationUser user = await _userManager.FindAsync(userName, password);

I believe I am actually missing some implementation of the UserManager .

I am working off an existing database that already has users created using Identity 2.0. My knowledge of ASP.NET 5 is limited, so I have just been following various guides and tutorials.


I used the same example to implement JWT token based authentication and ran exactly into the same problem. After performing some research, I'm quite sure that you are right - the UserManager does not seem to have a method validating username and password anymore.

The solution is quite simple yet in my opinion not very intuitive, which is why it took me some time to figure it out:

You can first check if a user with the given username exists using UserManager.FindByNameAsync and then check for a correct password using UserManager.CheckPasswordAsync .

My finished TokenController (inclduing the creation of an appropriate ClaimsIdentity which wasn't covered by the example as well) looks like this:

[Route("api/[controller]")]
public class TokenController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly TokenAuthOptions _tokenOptions;

    public TokenController(TokenAuthOptions tokenOptions, UserManager<ApplicationUser> userManager)
    {
        _tokenOptions = tokenOptions;
        _userManager = userManager;
    }

    public class AuthRequest
    {
        public string Username { get; set; }
        public string Password { get; set; }
    }

    [HttpPost]
    public async Task<dynamic> Post([FromBody] AuthRequest req)
    {
        var user = await _userManager.FindByNameAsync(req.Username);

        if (await _userManager.CheckPasswordAsync(user, req.Password))
        {
            DateTime? expires = DateTime.UtcNow.AddMinutes(2);
            var token = GetToken(req.Username, expires, user);
            return new { authenticated = true, entityId = user.Id, token = token, tokenExpires = expires };
        }
        return new { authenticated = false };
    }

    private async Task<string> GetToken(string userName, DateTime? expires, ApplicationUser user)
    {
        var handler = new JwtSecurityTokenHandler();

        var securityToken = handler.CreateToken(
            issuer: _tokenOptions.Issuer,
            audience: _tokenOptions.Audience,
            signingCredentials: _tokenOptions.SigningCredentials,
            subject: new ClaimsIdentity(await _userManager.GetClaimsAsync(user)),
            expires: expires
            );

        return handler.WriteToken(securityToken);
    }
}

I did some testing including role and claim based authentication and I'm pretty confident that everything works as intendet now.

链接地址: http://www.djcxy.com/p/22392.html

上一篇: 使用WebApi进行身份验证和授权

下一篇: Web API中的ASP.NET 5身份用户管理