ASP.net 5.0 - WebAPI Authorize & ErrorCode 302 instead of 401

I have an ASP.net 5.0 website (MVC 6) and use this site for some mobile applications. I have a controller that returns json data.

The user must authenticate to view this data, so I use the [Authorize] attribute for the controller.

I was expecting to get error 401 for unauthorized requests. I get a redirect (302) to the login page. In the mobile client, set the header only to receive "application / json" data, but I still get a redirect to the login page.

I developed a solution that works, but I'm not very happy with it. It works, but it's a kind of hack.

Is there a better solution for this?

Here is my solution (Configure method in Startup class)

//....Some Code app.Use(async (context, next) => { await next.Invoke(); if (context.Response.StatusCode == 302) { StringValues contentType; if (context.Request.Headers.TryGetValue("Accept", out contentType) && contentType.Contains("application/json")) { context.Response.StatusCode = 401; if (env.IsDevelopment()) await context.Response.WriteAsync("No Access"); } } }); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); 
+5
source share
1 answer

This must be authorized by the client. The client should send an X-Requested-With header with an XMLHttpRequest value.

So, this should be part of the header section in the HTTP request:

 X-Requested-With: XMLHttpRequest 

Now you will get 401 without hacks.

+2
source

Source: https://habr.com/ru/post/1237614/


All Articles