Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Web API 2 OWIN Bearer Token Authentication direct call

I have a problem with my Web Api Project. I have files stored in my Database and want to call them directly in a new window to view/save (URL like : /api/Files/5 - 5 beeing the FileId)

I got everthing working with the Bearer Token for my general AJAX requests with AngularJS for normal Data and it works like a charm. For the file I created a Controller that shows the file in the browser with the corresponding MIME-Type. But now that I changed the action to [Authorize] I get an Access Denied which is correct because I didnt pass an access_token in the HTTP-Header.

I did quite some research if it is possible to pass the Token via the querystring but didn't find anything helpful.

Now my plan is to remove the [Authorize] Attribute from my Controller and try to validate the token myself but I don't know how.

Anyone know how I can get it to work?

like image 660
Marvin Avatar asked Feb 21 '14 16:02

Marvin


1 Answers

I implemented bearer token authentication in my app (AngularJS, WebAPI 2) and I had similar problem - I needed to allow downloading files by clicking on a link. When you click on a link headers are not sent. :( So, I sent the token value in a query string to download a file

.../mywebapp/api/files/getfile/3?access_token=jaCOTrGsaak6Sk0CpPc1...

and set "Authorization" header to the token value in Startup.Auth.cs. Here is the code:

public void ConfigureAuth(IAppBuilder app)
{
    //It needs for file downloads
    app.Use(async (context, next) =>
    {
        if (context.Request.QueryString.HasValue)
        {
            if (string.IsNullOrWhiteSpace(context.Request.Headers.Get("Authorization")))
            {
                var queryString = HttpUtility.ParseQueryString(context.Request.QueryString.Value);
                string token = queryString.Get("access_token");

                if (!string.IsNullOrWhiteSpace(token))
                {
                    context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
                }
            }
        }

        await next.Invoke();
    });
    // Enable the application to use bearer tokens to authenticate users
    app.UseOAuthBearerTokens(OAuthOptions);
}
like image 197
Forward Avatar answered Feb 23 '23 14:02

Forward