.NET Web API 2 OWIN Bearer Token Authentication direct call

前端 未结 4 1912
天命终不由人
天命终不由人 2020-12-30 12:46

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

4条回答
  •  感动是毒
    2020-12-30 13:47

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

提交回复
热议问题