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