Asp.Net Core WebAPI Unauthorized Redirection

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; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework 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);
                        }
                    }
                };
            });

            //Add DI and other services
            SetServices(services);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        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()
{
     //logs in the user
}

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

+4
source share

All Articles