MBarto
MBarto

Reputation: 11

ASP.Net Core 2.2 Authentication

I'm trying to determine the best way to handle current authentication for my app. There isn't any authentication by my app but will be handled from a login page before getting to my app. If they successfully authenticate my app will receive a cookie containing credentials and other user information.

What's the best way to determine if the cookie is present throughout the users session? I am currently reading the cookie on the startup page but this causes issues if the user bookmarks a page past that. Should I be checking on each page request is the cookie is there or can I check up front when the user hits the default page and store that somehow?

Here's how I'm currently grabbing the user from the cookie

                UserId = _ltpaToken.LTPATokenParse();

                if (UserId == "")
                {
                    _logger.Error("No User found");
                    return RedirectToPage("/Error");
                }
                else
                {
                    HttpContext.Session.SetString("UserId", UserId);
                    return RedirectToPage();
                    //user is good to 
                }

Then checking for the UserId again on another page

            UserId = _httpContextAccessor.HttpContext.Session.GetString("UserId");

            if(UserId == null)
            {
                Response.Redirect("ToCompanyLoginPage");
            }

            //continue on to page load

Is there a better way to do this?

Upvotes: 1

Views: 907

Answers (2)

Hoshani
Hoshani

Reputation: 856

if you need something other than the default authentication you could use something like this

first create a simple user class

public class MyCustomUser
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string GivenName { get; set; }
}

in startup.cs inside ConfigureServices method

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromDays(7);
            options.LoginPath = "/Account/CustomLogin";
            options.Cookie.Name = "MyAuthCookieName";
        }
    );

in startup.cs inside Configure method

app.UseAuthentication();

then on your SignIn action in your controller you could write something like this that would save the information of the user in claims (what are claims?)

//Inside your SignIn method
    //User info should be taken from DB
    MyCustomUser user = new MyCustomUser()
    {
        Id = 1,
        Name = "Mr.Awesome",
        GivenName = "John Doe"
    };

    //Add user information
    List<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.Name),
        new Claim(ClaimTypes.GivenName, user.GivenName)
    };

    //Create the principal user from the claims
    ClaimsIdentity identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
    ClaimsPrincipal principal = new ClaimsPrincipal(identity);
    AuthenticationProperties authenticationProperties = new AuthenticationProperties() {IsPersistent = false};

    //Create the authentication cookie and store it
    await this.HttpContext
            .SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 
             principal, authenticationProperties);

   // DONE!

Upvotes: 1

Fatih Alac
Fatih Alac

Reputation: 16

var currentUserName = User.Identity.Name;

works everywhere, also roles are good way to go

var currentUserRole = User.IsInRole("Admin");

controller

public class PersonAuthorizationController : Controller
{
    private readonly SignInManager<IdentityUser> _signInManager;
    private readonly UserManager<IdentityUser> _userManager;
    private readonly MainDbContext _context;

    public PersonAuthorizationController(
        MainDbContext context, 
        UserManager<IdentityUser> userManager,
        SignInManager<IdentityUser> signInManager)
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _context = context;
    }

    // GET: Contact/PersonAuthorization
    public async Task<IActionResult> Index()
    {
        var currentUserId = _userManager.GetUserId(User);
        return View();
    }

Upvotes: 0

Related Questions