Home > Software engineering >  how to pass jwt token in header in asp.net core mvc
how to pass jwt token in header in asp.net core mvc

Time:10-18

in a project solution added on project asp.net core web api and another one core mvc.in api project created api for login and registraton and getting jwt token and in the mvc i m consuming api with httpClient,now i want to pass that to the header in order get result .so i stuck somwhere help me out this is api controller

  [Route("api/Authonticate")]
    public class AuthonticateController : Controller
    {
        private readonly ApplicationDbContext _db;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly IConfiguration _configuration;
        private readonly RoleManager<IdentityRole> _roleManager;
        public BinaryReader CliamTypes { get; private set; }

        public AuthonticateController(UserManager<ApplicationUser> userManager,
            IConfiguration configuration,
             RoleManager<IdentityRole> roleManager,
              ApplicationDbContext db)
        {
            _configuration = configuration;
            _userManager = userManager;
            _roleManager = roleManager;
            _db = db;
        }

        [HttpGet]
        [Route("Role")]
        public IQueryable<Object> Role()
        {
            var userRole = (from user in _db.Users
                            join userRoles in _db.UserRoles on user.Id equals userRoles.UserId
                            join role in _db.Roles on userRoles.RoleId equals role.Id
                           
                            select new { UserName = user.UserName, UserEmail = user.Email, userPhone = user.PhoneNumber, RoleName = role.Name });
            var s = userRole.ToList();
            return (userRole);
        }

        [HttpGet]
        [Route("GetRoles")]
        public List<IdentityRole> GetRoles()
        {
            return _roleManager.Roles.ToList();
        }

        [HttpPost]
        [Route("Registration")]
        public async Task<IActionResult> Register([FromBody]RegisterModel model)
        {
            var userExist = await _userManager.FindByEmailAsync(model.Email);
            if(userExist != null)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { status = "Error", message = "User Already Exist" });
            }
            ApplicationUser user = new ApplicationUser()
            {
                UserName = model.Name,
                Email = model.Email,
                PhoneNumber=model.PhoneNumber
            };
            var result=await _userManager.CreateAsync(user,model.Password);
            if (!result.Succeeded)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, new Response { status = "Error", message = "User Registration Failed!!" });
            }
            if (!await _roleManager.RoleExistsAsync(Roles.Admin))
                await _roleManager.CreateAsync(new IdentityRole(Roles.Admin));
            if(!await _roleManager.RoleExistsAsync(Roles.Employee))
                await _roleManager.CreateAsync(new IdentityRole(Roles.Employee));
            if( model.Role==Roles.Admin)
            {
                await _userManager.AddToRoleAsync(user, Roles.Admin);
            }
            else
            {
                await _userManager.AddToRoleAsync(user, Roles.Employee);
            }
            return Ok(new Response { status = "Sucess", message = "User Registration Sucessfull!!" });
         }

        [HttpPost]
        [Route("LogIn")]
        public async Task<IActionResult> LogIn([FromBody]LogInModel model)
        {
            var user=await _userManager.FindByEmailAsync(model.Email);
            if (user != null && await _userManager.CheckPasswordAsync(user,model.Password))
            {
                var userRoles = await _userManager.GetRolesAsync(user);
                var authClaims = new List<Claim>
                {
                    new Claim(ClaimTypes.Email, model.Email),
                    new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString())
                };
                foreach(var userRole in userRoles)
                {
                    authClaims.Add(new Claim(ClaimTypes.Role, userRole));
                }
                var authSignInKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:SecretKey"]));
                var token = new JwtSecurityToken(
                    issuer:_configuration["JWT:ValidIssuer"],
                    audience:_configuration["JWT:ValidAudience"],
                    expires:DateTime.Now.AddHours(3),
                    claims:authClaims,
                    signingCredentials:new SigningCredentials(authSignInKey,SecurityAlgorithms.HmacSha256)
                    );
                return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo });
            }
            return Unauthorized();
        }

        [HttpGet]
        [Route("LogOut")]
        public async Task<IActionResult> LogOut()
        {
            await HttpContext.SignOutAsync();
            return Ok(new { Message = "You are logged out" });

        }

now its my mvc controller

 [Area("Admin")]
    public class RegisterController : Controller
    {

        api _api = new api();

        public async Task<IActionResult> Index()
        {
         List<IdentityRole> roles = new List<IdentityRole>();
            HttpClient client = _api.Initial();
            HttpResponseMessage res = await client.GetAsync("api/Authonticate/GetRoles");
            if (res.IsSuccessStatusCode)
            {
                var result = res.Content.ReadAsStringAsync().Result;
                roles = JsonConvert.DeserializeObject<List<IdentityRole>>(result);
            }
            ViewBag.RoleList = roles.Select(i => new SelectListItem
            {
                Value = i.Id.ToString(),
                Text = i.Name
            });

            return View();
        }
        [HttpPost]
        public IActionResult Index(RegisterModel model)
        {
            HttpClient client = _api.Initial();
            var postTalk = client.PostAsJsonAsync("api/Authonticate/Registration", model);
            postTalk.Wait();
            var result = postTalk.Result;
            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index", "Home" ,new { Area = "Employee" });
            }
            return View();
        }
        [HttpGet]
        public IActionResult LogIn()
        {
            return View();
        }
        [HttpPost]
        public IActionResult LogIn(LogInModel log)
        {
            HttpClient client = _api.Initial();
            var postTalk = client.PostAsJsonAsync("api/Authonticate/LogIn/", log);
            postTalk.Wait();
            var result = postTalk.Result;
            if (result.IsSuccessStatusCode)
            {
                return RedirectToAction("Index", "Home", new {Area="Employee"});
            }
            return View();
        }


        public async Task<IActionResult> LogOut()
        {
            HttpClient client = _api.Initial();
            HttpResponseMessage res = await client.GetAsync($"api/Authonticate/LogOut");

            if (res.IsSuccessStatusCode)
            {
                return RedirectToAction("Index", "Home", new { Area = "Employee" });
            }
            return NotFound();
        }
    }

and the helper class is

 public HttpClient Initial()
        {
            var client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44324/");
            return client;
        }

now how i to pass the token to header

CodePudding user response:

string token="your token"; 
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");

CodePudding user response:

So your MVC application does HTTP request to your WebApi? And the JWT authenticates not with the MVC application but with the WebApi? First of all I wonder why you have the MVC application in between. A client side app (in Vue.js, React, Angular, etc) seems more appropriate.

But if you want to keep it serverside, then I'd suggest the MVC app should store the JWT in the user's session:

In your MVC controller, method LogIn:

//Do LogIn on WebApi
Session["JWT"] = result;

Then on the HttpClient:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Session["JWT"]);

From here: Building post HttpClient request in C# with Bearer Token

Maybe first verify that Session["JWT"] actually contains a token before attempting to use it on the WebApi.

  • Related