Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a ASP.net 5.0 (MVC 6) Website and use this website also for some mobile apps. I have a controller that returns json data.

The User has to Authenticate to see this data so I use the [Authorize] attribute for the Controller.

I expected to get an Error 401 for not authorized requests nur I get an redirect (302) to the loginpage. In the Mobile Client a set the header to only accept "application/json" data but I still get the redirect to the login page.

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

Is there a better solution to handle this?

Here 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?}");
        });
like image 923
3 revs Avatar asked Sep 27 '22 00:09

3 revs


1 Answers

This should be solved by the client. The client have to send a X-Requested-With header with the value XMLHttpRequest.

So this should be a part of the headers section in the HTTP request:

X-Requested-With: XMLHttpRequest

Now you'll get your 401's without hacks.

like image 158
Niels Ladegaard Beck Avatar answered Oct 11 '22 17:10

Niels Ladegaard Beck