Asp.Net Core WebAPI重定向未经授权

时间:2016-07-01 07:42:47

标签: asp.net asp.net-web-api response.redirect

我正在使用asp.net核心。我需要在我的网络API上重定向未经授权请求的响应。我找到了一些解决方案并试图实现它,但仍然无效。任何人都可以帮助我。

这是我的代码:

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

两种控制器的方法。

[HttpGet]
[Route("test")]
public string Test()
{
     return "authorized";
}


[HttpGet]
[Route("login")]
[AllowAnonymous]
public async Task<IActionResult> Login()
{
     //logs in the user
}

这是因为我在Startup.cs的COnfigure方法中不使用app.UseIdentity()吗?

我没有使用EF的身份证,我没有在任何地方使用EF。

然后我尝试了这个:

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

没有效果。

日Thnx

0 个答案:

没有答案