I work with asp.net core. I need to redirect a response to an unauthorized request on my api website. I found some solution, and I tried to implement it, but still does not work. Can someone help me.
Here is my code:
public partial class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc(options =>
{
options.Filters.Add(new RequireHttpsAttribute());
})
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
services.Configure<IdentityOptions>(options =>
{
options.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/Login");
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if ( (ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.Value.Contains("Account/Login") && ctx.Response.StatusCode == 200) )
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.FromResult<object>(null);
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
}
};
});
SetServices(services);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseDeveloperExceptionPage();
CookieAuthenticationOptions options = new CookieAuthenticationOptions();
options.AuthenticationScheme = "Cookies";
options.CookieName = "GUW Cookie";
options.AutomaticAuthenticate = true;
options.AutomaticChallenge = true;
options.LoginPath = new PathString("/Account/Login");
app.UseCookieAuthentication(options);
app.UseMvc();
}
}
And two methods for controlling controllers.
[HttpGet]
[Route("test")]
public string Test()
{
return "authorized";
}
[HttpGet]
[Route("login")]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
}
Is it because I am not using app.UseIdentity () in my COnfigure method in Startup.cs?
I do not use Identity from EF, I do not use EF anywhere.
Then I tried this:
services.Configure<CookieAuthenticationOptions>(options =>
{
options.Events = new CookieAuthenticationEvents()
{
OnRedirectToLogin = ctx =>
{
if ( ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
{
ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Task.FromResult<object>(null);
}
else
{
ctx.Response.Redirect(ctx.RedirectUri);
return Task.FromResult<object>(null);
}
}
};
});
There are no effects.
Thnx
source
share