1

After signing in, why am I never authenticated?

I created a custom authorize attribute where I am handling the log in. I also tried putting similar code in middleware. I can't seem to get it working.

My Startup class:

   public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie();

        services.AddTransient<IUserStore<ApplicationUser>, UserStore>();
        services.AddTransient<IRoleStore<ApplicationRole>, RoleStore>();

        services.AddIdentity<ApplicationUser, ApplicationRole>()
            .AddDefaultTokenProviders();

        services.AddRazorPages();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }

My custom authorization:

[AttributeUsage(AttributeTargets.Class)]
    public class CustomAuthorization : Attribute, IAsyncAuthorizationFilter
    {
        public async Task OnAuthorizationAsync(AuthorizationFilterContext filterContext)
        {
            if (filterContext != null)
            {
                await filterContext.HttpContext.SignOutAsync();

                var validator = new JwtSecurityTokenHandler();

                // get the token from query
                var query = HttpUtility.ParseQueryString(filterContext.HttpContext.Request.QueryString.Value);

                // validate token here

                var isLoggedIn = filterContext.HttpContext.User.Identity.IsAuthenticated;
                if (!isLoggedIn)
                {
                    if (!query.AllKeys.Contains("token") || !validator.CanReadToken(query.Get("token")))
                    {
                        filterContext.HttpContext.Response.Redirect("https://external-login");
                    }
                    else
                    {
                        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                        identity.AddClaim(new Claim(ClaimTypes.Name, "Name"));
                        identity.AddClaim(new Claim(ClaimTypes.Email, "test@test.com"));

                        var principal = new ClaimsPrincipal(identity);

                        await filterContext.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                        if (filterContext.HttpContext.User.Identity.IsAuthenticated)
                            filterContext.HttpContext.Response.Redirect("/");
                    }
                }

                return;
            }
        }
    }

Which I am using on my index page:

[CustomAuthorization]
public class IndexModel : PageModel
Primico
  • 2,143
  • 3
  • 24
  • 36
  • What happens after you sign in? Do you move to the next page? if yes, are you able to see the Cookie in the developer tools of the browser? If you are not moving to the next page, are you getting any error or warning in the browser console or on the page? If possible, could you try to debug the code to see at which step code execution stops. It may help narrow down the issue. – Deepak-MSFT Apr 14 '22 at 02:56
  • Please post your **actual** `Startup`'s `ConfigureServices` and `Configure` methods _separately_, instead of just mashing them together in your post. – Dai Apr 14 '22 at 15:08
  • Show us where you're using `CustomAuthorization`. Also, you shouldn't be performing authorization logic inside an `Attribute` subclass. Instead, _do it properly_ by following this guide: https://stackoverflow.com/questions/31464359/how-do-you-create-a-custom-authorizeattribute-in-asp-net-core – Dai Apr 14 '22 at 15:11
  • Thanks for the advice about the proper way to create a policy for my authorize attribute. I will make that change after I can get my sign in working. – Primico Apr 14 '22 at 15:24
  • As the word 'not working' not giving much idea, If you could share the information I asked in my previous comment then based on that we could try to provide further suggestions. – Deepak-MSFT Apr 15 '22 at 03:09

0 Answers0