aidrivenpost
aidrivenpost

Reputation: 1943

Claims Authentication ASP.NET vNext

When adding a claim to the user, the claims information does not get recorded as a cookie on the page and the information gets lost for all other requests. Why does this happen?

    public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null)
    {
        if (ModelState.IsValid)
        {
            try
            {
                var authReq = new AuthenticationViewModel() { password = model.Password, username = model.UserName };
                var userInfo = await _dataService.AuthenticateAsync(authReq);


                var claims = new List<Claim>();
                claims.Add(new Claim("username", userInfo.user.userName));
                claims.Add(new Claim("AddtionalData", userInfo.AddtionalData));

                var user = ClaimsPrincipal.Current;

                var identity = user.Identities.Where(x => x.AuthenticationType == "Custom").FirstOrDefault();

                if (identity == null)
                    identity = new ClaimsIdentity(claims.ToArray(), "Custom");

                user.AddIdentity(identity);


                return RedirectToAction("Users", "Index");
            }
            catch (Exception)
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

Upvotes: 2

Views: 1766

Answers (1)

aidrivenpost
aidrivenpost

Reputation: 1943

I found the issue, I needed to add the following code:

context.Response.SignIn(new ClaimsIdentity(new[] { new Claim("name", "bob") }, CookieAuthenticationDefaults.AuthenticationType)); 

also, I changed the AuthenticationType to be CookieAuthenticationDefaults.AuthenticationType.

Please see link with Sample

Upvotes: 2

Related Questions