0

This is how I authenticate and sign in my user:

public void UserAuthentication(string email)
{  
    var claim = new List<Claim> { new Claim(ClaimTypes.Name, email) };
    var identity = new ClaimsIdentity(claim, CookieAuthenticationDefaults.AuthenticationScheme);
    var principal = new ClaimsPrincipal(identity);
    HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal).Wait();
}

I want to ask, can this method fail? If so, how can I handle it?

dekanidze
  • 132
  • 2
  • 9
  • Posting part of method won't give you right answer. – Adlorem Nov 17 '20 at 00:08
  • Updated my code. I send user's entered email to this method and I claim it as a name so I can refer to `User.Identity.Name` in my app. Believe this code can fail sometimes as `User.Identity.Name` can return me null or `User.Identity.IsAuthenticated` can be false. So I want to catch this failure here. How can I achieve that? – dekanidze Nov 17 '20 at 00:18
  • `User.Identity.Name can return me null or User.Identity.IsAuthenticated can be false` When you meet this issue? According to your code and description, it seems that you want to use cookie authentication without Asp.net core Identity, right? If that is the case, perhaps the cookie is expired, please check it. Besides, here are some related articles about cookie authentication, you could refer them:[Link 1](https://www.c-sharpcorner.com/article/cookie-authentication-in-net-core-3-0/) and [Link 2](https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-5.0). – Zhi Lv Nov 17 '20 at 03:34
  • I would meet this issue if this method somehow fail in authentication. Unless it is impossible. I am using cookie authentication here. Just want to know if it can fail. I read something about `AuthenticateResult` but not sure how to use it or if it is even useful to use in here. – dekanidze Nov 17 '20 at 04:00
  • Perhaps you want to create a custom cookie AuthorizationHandler to validate the claims, check the following articles: [Exploring the cookie authentication middleware in ASP.NET Core](https://andrewlock.net/exploring-the-cookieauthenticationmiddleware-in-asp-net-core/) and [ASP.NET Core 2.0 custom middleware using cookie authentication](https://stackoverflow.com/questions/46938511/). – Zhi Lv Nov 17 '20 at 06:24
  • @ZhiLv thank you, the second link is something I wanted to know – dekanidze Nov 17 '20 at 07:17

0 Answers0