Recently I was working on an ASP.NET Core 8 project where I needed to implement Google Login without Identity. I did a Google search and came across this article: Use social sign-in provider authentication without ASP.NET Core Identity
I implemented this and and the login worked fine. Next I added an API controller requiring authorization and when I called it from the frontend without logging in it was returning a redirect response instead of error 401.
To fix this we need to use a customer handler for OnRedirectToAuthorizationEndpoint
event where we can return error 401 if the request path starts with /api
. See the below snippet.
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(options =>
{
options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
options.Events.OnRedirectToAuthorizationEndpoint = ctx =>
{
if (ctx.Request.Path.StartsWithSegments("/api"))
{
if (ctx.Response.StatusCode == (int)HttpStatusCode.OK)
{
ctx.Response.StatusCode = 401;
}
} else
{
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult(0);
}
return Task.CompletedTask;
};
});
If you know of an alternative way to implement this do let me know in the comments.
Top comments (0)