locked
ASP.NET Core 2.0 Cookie Authentication Login RRS feed

  • Question

  • User-1434682318 posted

    Having an issue with Cookie Authentication without Identity.

    Using:

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddAuthorization(options =>
                {
    
                    options.AddPolicy(Constants.CONST_POLICY_SUPERADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_SUPERADMIN));
                    options.AddPolicy(Constants.CONST_POLICY_ADMIN, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN));
                    options.AddPolicy(Constants.CONST_POLICY_DIR, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR));
                    options.AddPolicy(Constants.CONST_POLICY_HoD, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR, Constants.CONST_ROLE_HoD));
                    options.AddPolicy(Constants.CONST_POLICY_STAFF, policy => policy.RequireRole(Constants.CONST_ROLE_ADMIN, Constants.CONST_ROLE_SUPERADMIN, Constants.CONST_ROLE_DIR, Constants.CONST_ROLE_HoD, Constants.CONST_ROLE_STAFF));
                });
    
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options =>
                {
    
                    options.LoginPath = new PathString("/Account/Login/");
                    options.AccessDeniedPath = new PathString("/Account/Forbidden/");
    
                });
            }

    When accessing, user will always be directed to the AccessDeniedPath . If I navigate to the LoginPath the user is logged in correctly.

    Looking at the cookie, it shows an expiry date of 1970-01-01.

    Cannot get it to direct to the LoginPath ,Competely stumped.

    Monday, February 26, 2018 11:48 AM

All replies

  • User354416029 posted

    Depends on what response is generated for request, If your request generates 403 response then This code will always redirect you to AccessDenied Path.

    however if you get 401 Unauthorized response you will be redirected to login Path. so you need to check what response is generated for your request.

    Thanks,

    Chintan

    *Please mark it as answer if appropriate*

    Monday, February 26, 2018 7:56 PM
  • User-1434682318 posted

    It is showing 401 Unauthorised response, then directing to AccessDenied

    Tuesday, February 27, 2018 9:01 AM
  • User283571144 posted

    Hi ElTodge,

    According to your description, we couldn't directly find the reason why the auth is failed.

    Could you please post the details codes about the login?

    Have you set the ExpiresUtc property?

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, user.Email),
        new Claim("FullName", user.FullName)
    };
    
    var claimsIdentity = new ClaimsIdentity(
        claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    var authProperties = new AuthenticationProperties
    {
        //AllowRefresh = <bool>,
        // Refreshing the authentication session should be allowed.
    
        //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
        // The time at which the authentication ticket expires. A 
        // value set here overrides the ExpireTimeSpan option of 
        // CookieAuthenticationOptions set with AddCookie.
    
        //IsPersistent = true,
        // Whether the authentication session is persisted across 
        // multiple requests. Required when setting the 
        // ExpireTimeSpan option of CookieAuthenticationOptions 
        // set with AddCookie. Also required when setting 
        // ExpiresUtc.
    
        //IssuedUtc = <DateTimeOffset>,
        // The time at which the authentication ticket was issued.
    
        //RedirectUri = <string>
        // The full path or absolute URI to be used as an http 
        // redirect response value.
    };
    
    await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme, 
        new ClaimsPrincipal(claimsIdentity), 
        authProperties);

    Besides, I suggest you could follow this tutorial to enable the cookie auth without identity.

    https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?tabs=aspnetcore2x 

    Best Regards,

    Brando

    Wednesday, February 28, 2018 8:05 AM
  • User-1434682318 posted

    For Ref this is the Login:

    [AllowAnonymous]
            public async Task<IActionResult> Login(string returnUrl = null)
            {
                string name = User.Identity.Name;
                int index = name.IndexOf('\\') + 1;
    
                string username = name.Substring(index, name.Length - index);
    
                await LoadDataFromAD(username);
    
                return RedirectToLocal(returnUrl);
            }
    
     private async Task LoadDataFromAD(string username)
            {
                List<string> PropertiesToGet = new List<string>();
                PropertiesToGet.Add("employeeid");
                PropertiesToGet.Add("division");
                PropertiesToGet.Add("cn");
    
                WCFLDAP.LDAPClient wcfLDAP = new WCFLDAP.LDAPClient();
                await wcfLDAP.OpenAsync();
    
                List<string> aList = wcfLDAP.GetADUserProperties(_AppSettings.WebServiceCode, username, PropertiesToGet);
    
                if (aList.Count > 0)
                {
                    var claims = new List<Claim>();
                    claims.Add(new Claim(ClaimTypes.WindowsAccountName, username, ClaimValueTypes.String, Issuer));
                    claims.Add(new Claim(ClaimTypes.Name, aList[2], ClaimValueTypes.String, Issuer));
                    claims.Add(new Claim("employeeid", aList[0], ClaimValueTypes.String, Issuer));
                    if (aList[1].ToLower() == "student")
                    {
                        claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_STUDENT, ClaimValueTypes.String, Issuer));
                    }
                    else
                    {
                        if (wcfLDAP.IsUserInTheGroup(_AppSettings.WebServiceCode, username, "IT Development SG"))
                            claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_SUPERADMIN, ClaimValueTypes.String, Issuer));
                        else if (wcfLDAP.IsUserInTheGroup(_AppSettings.WebServiceCode, username, "SAR Administrators SG"))
                            claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_ADMIN, ClaimValueTypes.String, Issuer));
                        else if (wcfLDAP.IsUserInTheGroup(_AppSettings.WebServiceCode, username, "SAR Executive SG"))
                            claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_DIR, ClaimValueTypes.String, Issuer));
                        else if (wcfLDAP.IsUserInTheGroup(_AppSettings.WebServiceCode, username, "SAR Owners SG"))
                            claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_HoD, ClaimValueTypes.String, Issuer));
                        else
                        {
                            claims.Add(new Claim(ClaimTypes.Role, Constants.CONST_ROLE_STAFF, ClaimValueTypes.String, Issuer));
                        }
    
                    }
    
                    var userIdentity = new ClaimsIdentity("OaklandsLogin");
                    userIdentity.AddClaims(claims);
    
                    var userPrincipal = new ClaimsPrincipal(userIdentity);
    
                    await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal,
                        new AuthenticationProperties
                        {
                            ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
                            IsPersistent = false,
                            AllowRefresh = false
                        });
                }
    
                await wcfLDAP.CloseAsync();
            }

    This all works and will log the user in, the problem is that the LoginPath is not being followed and none of this code is accessed. If I point the AccessDeniedPath at /Account/Login/, then it hits this and the user is logged in without issue.

    Wednesday, February 28, 2018 9:16 AM
  • User283571144 posted

    Hi ElTodge,

    This all works and will log the user in, the problem is that the LoginPath is not being followed and none of this code is accessed. If I point the AccessDeniedPath at /Account/Login/, then it hits this and the user is logged in without issue.

    Do you mean if you firstly access the /account/login, then it will generate the right cookie?

    You could access all the page well.

    Normally, we will show the login path in the accessed denied path to redirect user to login in.

    Best Regards,

    Brando

    Thursday, March 1, 2018 6:24 AM
  • User-1434682318 posted

    If I set the following:

    options.LoginPath = new PathString("/Account/Login/");
    options.AccessDeniedPath = new PathString("/Account/Login/");

    It still does not route via the LoginPath, but follows the AccessDenied to the Login method. Using breakpoints I can see that it is the AccessDenied path that is followed.

    This has been fine during devolpment, but obviously not ideal as there is no Forbidden option for invalid users.

    Cheers,

    ElTodge

    Thursday, March 1, 2018 8:58 AM
  • User283571144 posted

    Hi ElTodge,

    In my opinion, if user doesn't login in it will automatic redirect to the access accessDenied page.

    It works well.

    Normally, we will show the login page redirect url inside the accessDenied page to mention the user to login in.

    Best Regards,

    Brando

    Monday, March 19, 2018 1:58 AM