Search code examples
c#asp.net-coreasp.net-identity

How to get the bearer token using Microsoft Identity


I have created a controller for Login and there is an endpoint for authentication. I am using Microsoft.AspNetCore.Identity;

enter image description here

Here is the code for this controller

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;

[Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public LoginController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> LoginAsync([FromBody] LoginRequest userLogin)
        {         
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(userLogin.Username, userLogin.Password, isPersistent: false, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                 // code removed for brevity                   
                }               
            }
            return BadRequest();
        }
    }

How do I get the bearer token from result? I wish to return back the token bearer as a response if /api/Login post request is successful.


Solution

  • SignInManager<TUser>.PasswordSignInAsync Method Attempts to sign in the specified userName and password combination as an asynchronous operation and return Task<SignInResult>. for bearer token use CheckPasswordAsync. its return a flag indicating whether the given password is valid for the specified user.

    _userManager.CheckPasswordAsync(user, model.Password)
    

    if user has valid creadintial then generate the token.

                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    var userRoles = await _userManager.GetRolesAsync(user);
    
                    var authClaims = new List<Claim>
                    {
                        new Claim(ClaimTypes.Name, user.UserName),
                        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                    };
    
                    foreach (var userRole in userRoles)
                    {
                        authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                    }
    
                   var token = GetToken(authClaims);
    
                    return Ok(new
                    {
                        token = new JwtSecurityTokenHandler().WriteToken(token),
                        expiration = token.ValidTo
                    });
                }
    

    Ref: Link1, Link2, Link3, Link4