Click here to Skip to main content
15,065,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,
I currently have 2 separate projects, I have an API for the backend with CRUD and login functionality, I also set up Json Web Tokens on the backend for validation purposes.
I have a front end MVC project which I am using for my UI. On this front end I have my login page where a user logins in and the API sends back a JWT token.

C#
// API
        private string GenerateToken(string user)
        {
            var secretKey = configuration.GetValue<string>("Tokens:Key");
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256Signature);
            var claims = new Claim[]
            {
               // new Claim(JwtRegisteredClaimNames.Sub, user.Id),
                new Claim(JwtRegisteredClaimNames.UniqueName, user)//user.UserName),
               // new Claim(JwtRegisteredClaimNames.Email, user.Email)

            };
            var jsonToken = new JwtSecurityToken(
                                signingCredentials: signingCredentials,
                                claims: claims,
                                expires: DateTime.UtcNow.AddMinutes(5),
                                audience: this.configuration.GetValue<String>("Tokens:Audience"),
                                issuer: this.configuration.GetValue<String>("Tokens:Issuer")
                              );

            return new JwtSecurityTokenHandler().WriteToken(jsonToken);

        }

        [AllowAnonymous]
        [HttpPost("Authenticate")]
        //public async Task<IActionResult> Authenticate(string username, string password)
        public async Task<IActionResult> Authenticate(LoginModel loginModel)
        {
            if (!string.IsNullOrWhiteSpace(loginModel.Username) && !string.IsNullOrWhiteSpace(loginModel.Password))
            {
                var result = await signInManager.PasswordSignInAsync(loginModel.Username, loginModel.Password, false, false);
                if (result.Succeeded)
                {
                    return Ok(GenerateToken(loginModel.Username));
                }
                //return BadRequest(ModelState.AddModelError("Login Fail", "invalid credentials"));
                return BadRequest("Login Fail");
            }
            return BadRequest();
        }
// front end
        [HttpPost]
        public async Task<IActionResult> Login(LoginModel loginModel)
        {
            if (ModelState.IsValid)
            {
                var model = JsonConvert.SerializeObject(loginModel);
                var client = apiClient.CreateClient();

                HttpRequestMessage httpRequest = new HttpRequestMessage
                {
                    Content = new StringContent(model, Encoding.UTF8, "application/json"),
                    RequestUri = new Uri($"https://localhost:5001/api/Account/Authenticate"),
                    Method = new HttpMethod("Post")
                };

                var response = await client.SendAsync(httpRequest);
                if (response.IsSuccessStatusCode)
                {
                    return RedirectToAction("Success","Home",null);
                }
            }

            return View("Failure");
        }


What I have tried:

Once I get this token I want the user to be able to access a secure page that only works with a valid login. I put [Authorize] on this new page, How do I do this in this circumstance? Do I have to add my same JWT properties to the front end and validate it there? Or do I create a validate method in the API and if successful then allow the user to go to the page. But with this way [Authorize] on front end wouldn’t work… I could add my JWT to a cookie on the front end but I don’t understand how to validate it on front end. The project wouldn’t have to talk back to my API to access the user portal page. Here is my code for my API and the front end. Both are C# projects.
Posted
Comments
Vikram Motwani 4-Jan-21 10:58am
   
Try checking this article, it provides all the details of JWT auth
https://www.codeproject.com/Articles/5247609/ASP-NET-CORE-Token-Authentication-and-Authorizat-2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900