在标头GET方法中发送令牌

时间:2016-05-31 17:39:00

标签: angularjs image get header asp.net-web-api2

有一个网站和一个网络API。我从web api服务器收到的所有文件。

我在网站上有一个ADFS OAUTH2授权。 我需要使用auth令牌从web api获取图像。

所以现在我做这样的事情:

<img src='webApiUrl/Photo/Id?token=token_value' alt />

但我有一个令牌长度的错误。对于一些客户来说这很长,我无法控制它。 我可以使用xhr请求发送授权标头但我不明白如何为通过src从html请求资源的站点设置授权标头。

你能帮我解决一下吗?

2 个答案:

答案 0 :(得分:0)

每当您对Web API发出HTTP请求时,您都可以使用Angular Interceptor将令牌放在请求标头上。在这里,我选择演示Bearer身份验证。像这样:

appName.config(["$httpProvider", ($httpProvider: ng.IHttpProvider) => {
                $httpProvider.interceptors.push(<any>["$q", "$location",
                    ($q: ng.IQService, $location: ng.ILocationService) => {
                        return {

                     // config is the request data, including all its properties
                            'request': (config) => {

                               // Intercepting only the API requests
                                if (config.url.indexOf(apiServerUrl) >= 0) {

                               // Getting the token from local storage for example
                                    var token = localStorage.getItem("token"); 

                               // Placing the token in the right header                                        
                                   if (token)
                                     config.headers["Authorization"] = "Bearer " + token; 
                                }
                                return config;
                            }
                        }
                    }
                ]);
            }]);

答案 1 :(得分:-1)

也许这可以解决您的问题:http://blog.jsgoupil.com/request-image-files-with-angular-2-and-an-bearer-access-token/

它涉及注册管道,以便您可以对src标记使用安全的img属性。

相关问题