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

anonymous User with password-protected link in asp.net core 3.1 - is ClaimsPrinciple/cookie the best way to do this?

$
0
0

ok - so im trying to do something like vimeo.com
where a private video can be accessed by just inputting a password
so for example if you go here:
https://vimeo.com/392083444
you get a simple password box and submit button

i came to the conclusion to use claims
since the user is anonymous - i didnt want to use Identity
in addition the video password is saved in the db with the video metadata

oh and btw just like vimeo or youtube -
there is a proper Identity setup bc the profile is governed by a proper Identity login

so the first question is:
is going with ClaimsPrinciple the best strategy to do this?
or am i making too much out of it ?
i mean pre-Core i would have gone with session vars but thats not a thing now in core

heres what ive got so far

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> LinkLogin([Bind("ID, Guid, Password")] LinkLoginVM vm)
    {
        if (String.IsNullOrEmpty(vm.Password))
        {
            return ViewComponent("Error", new { errorcode = 1});
        }
        var c = await db.Vids.SingleAsync(c => c.Guid == vm.Guid);

        // create and add guid
        if (ModelState.IsValid)
        {
            if (vm.Password == c.Password)
            {
                // give user a claim
                ApplicationUser user = await um.GetUserAsync(HttpContext.User);  <-- this doesnt really return anything
                var claims = new List<Claim>() { 
                    new Claim(ClaimTypes.Name, "Password Guest"),
                    new Claim(JwtRegisteredClaimNames.Sub, vm.Guid),
                    new Claim(JwtRegisteredClaimNames.AuthTime, DateTime.Now.ToString())
                };

                // not sure what im doing here
                var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
//               await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProps);
                await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity), authProps);
            }
        }
        else
        {
            // put debugger here if problematic
            Console.WriteLine("ERR: ModelState not valid");
            var errors = ModelState
                .Where(x => x.Value.Errors.Count > 0)
                .Select(x => new { x.Key, x.Value.Errors })
                .ToArray();
        }

        return RedirectToAction("Vids", new { id = vm.Guid });
    }

in my startup im sure i messed something up -
cause i feel like all im reading a bunch of spaghetti code in the articles
and with the constant version changes even some articles from a year ago are out of date

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
        {
            options.LoginPath = "/View/LinkLogin/";
            options.LogoutPath = "/Account/Logout/";
            //options.Cookie.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = environment.IsDevelopment() ? Microsoft.AspNetCore.Http.CookieSecurePolicy.None : Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
            options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
        });

        services.ConfigureApplicationCookie(options =>
        {
            // Cookie settings
            options.Cookie.HttpOnly = true;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(35);

            //could be - 
            //options.LoginPath = "/Identity/Account/Login";
            //options.LogoutPath = "/Identity/Account/Logout";
            //options.AccessDeniedPath = "/Identity/Account/AccessDenied";
            options.LoginPath = $"/Identity/Account/Login";
            options.LogoutPath = $"/Identity/Account/Logout";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
            options.SlidingExpiration = true;
        });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddRazorPagesOptions(options =>
            {
                // deprecated  in3.1?
                // options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
                options.Conventions.AuthorizeFolder("/View");
            });

and then later

        // routing and security
        app.UseRouting();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseEndpoints(endpoints =>  etc...

im referencing these articles:
https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1
https://www.yogihosting.com/aspnet-core-identity-claims/
https://www.red-gate.com/simple-talk/dotnet/net-development/using-auth-cookies-in-asp-net-core/

the claims get processed but they dont get stored
is it even possible to store these claims with an anonymous user
if yes where should i be looking for them with an anonymous user?
if no what should i be doing next?


Viewing all articles
Browse latest Browse all 9386

Trending Articles



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