Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

how to generate anti-forgery token in api?

$
0
0

so I followed the instructions here   and this what i did so far in my startup.cs

          services.AddAntiforgery(options =>
                    {
                    options.HeaderName = "X-XSRF-TOKEN";
                    options.SuppressXFrameOptionsHeader = false;
                    });

and in config section,

 app.UseAntiforgeryToken();

now how do I push for generating this cookie?

my login api looks like,

       [HttpPost]
        [AllowAnonymous]
        // [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login([FromBody] CredentialsViewModel credentials)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var result = await signInManager.PasswordSignInAsync(credentials.UserName, credentials.Password, credentials.RememberMe, lockoutOnFailure: true);
            if (result.Succeeded)
            {
                await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);
                var userToVerify = await userManager.FindByNameAsync(credentials.UserName);
                var accessToken = new AccessTokenViewModel();
                (accessToken.AuthToken, accessToken.TokenId) = await _tokenStoreService.CreateJwtTokens(userToVerify).ConfigureAwait(false);
                // var claims = new List<Claim>
                //              {
                //              new Claim(ClaimTypes.Hash, accessToken.AuthToken),
                //              new Claim(ClaimTypes.Authentication, accessToken.AuthToken),

                //              };
                // var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                // await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                //    new ClaimsPrincipal(claimsIdentity));
                logger.LogInformation("User logged in.");

                return Ok(accessToken);
            }
            if (result.RequiresTwoFactor)
            {

                return BadRequest("RequiresTwoFactor.");
            }
            if (result.IsLockedOut)
            {
                logger.LogWarning("User account locked out.");
                return BadRequest("User account locked out.");
            }
            else
            {
                // ModelState.AddModelError("error", "Invalid login attempt.");
                // return BadRequest(ModelState);
                logger.LogCritical("Unable to register a user");
                return BadRequest("Unknown error occured during registration, Please contact the database administrator");
            }
        }


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>