How to Set value in Http Request Header - javascript

I am dealing with cross origin request to access my restful API's,so i want to set field "Authorization" in http request header on every request,but is not going to set in header...so what am doing wrong here?
My app.js
'use strict';
var app = angular.module('samepinch', [
'ngResource',
'ngCookies',
'ui.router',
'toaster',
'ui.bootstrap',
'oc.lazyLoad',
'samepinch.controllers',
'samepinch.directives',
'samepinch.factory',
'samepinch.services',
// Added in v1.3
'FBAngular',
'Config',
'samepinch.login',
'samepinch.item',
'samepinch.common'
]);
angular.module('samepinch.login',[]);
angular.module('samepinch.item',[]);
angular.module('samepinch.common',[])
app.run(function($http)
{
$http.defaults.headers.common.Authorization = '';
// Page Loading Overlay
public_vars.$pageLoadingOverlay = jQuery('.page-loading-overlay');
jQuery(window).load(function()
{
public_vars.$pageLoadingOverlay.addClass('loaded');
})
});
Controller is
angular.module('samepinch.login').controller('LoginController',['$scope','LoginService','$rootScope','$http',function($scope,LoginService,$rootScope,$http){
$rootScope.isLoginPage = true;
$rootScope.isLightLoginPage = false;
$rootScope.isLockscreenPage = false;
$rootScope.isMainPage = false;
$scope.register = function(credentials){
$http.defaults.headers.common.Authorization = 'dfdfdf';
LoginService.post(credentials,function(success){
},function(error){
});
}
}]);
My Service is
'use strict';
angular.module('samepinch.login').factory('LoginService', ['$resource','$enviornment', function ($resource,$enviornment) {
var url = $enviornment.backendurl;
return $resource(url+'authenticate',{},{
query: {
method:'GET',
params:{itemId:''},
isArray:true
},
post: {
method:'POST',
headers: {
'Authorization': 'Basic dGVzdDp0ZXN0',
'Content-Type': 'application/json'
}
},
update: {
method:'PUT', params: {itemId: '#entryId'}
},
remove: {
method:'DELETE'
}
});
}]);
My Http request looks like
Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/api/v1/authenticate
Request Method:OPTIONS
Status Code:401 Unauthorized
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:9006
Pragma:no-cache
Referer:http://localhost:9006/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36
Response Headersview source
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE,PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Length:0
Date:Wed, 22 Jul 2015 07:52:15 GMT
Expires:0
Pragma:no-cache
Server:Apache-Coyote/1.1
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block
So 'Authorization' field is not set in headers..please help me what am i missing here

This log is for OPTIONS request
Request Method:OPTIONS
First you need to setup your server to return 200 OK for OPTIONS call then the POST call with proper parameters will be send
Look for instructions here http://enable-cors.org/ how to configure CORS (including OPTIONS request) on your architecture

Related

OPTIONS Method not allowed. Get Works but not POST

I am using angularJS and this is my code in a factory which makes a http POST call
var data = { ticket: JSON.stringify(aticket), "autoAssignDefaultSLA": "true", "autoAssignDefaultPriority": "true" };
return $http({
method: 'POST',
url: requestUrl,
data: data,
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
});
An http GET call works and I get json back with no issues
return $http({
method: 'GET',
url: requestUrl,
params: { userToken: userToken, assignedIds: contactId, companyIds: "" }
});
By setting the Content-Type to application/json an OPTIONS request is sent out. So far in my tests it appears that setting the content type to "application/x-www-form-urlencoded" is not possible because the web service will only accept json data. I do not have access to modify the web service code. Another team takes care of that.
The request headers that goes with OPTIONS is
Host: staging.url.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
DNT: 1
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: https://url.synbeta.com
Connection: keep-alive
The response headers is as follows
Access-Control-Allow-Headers: Authorization, Content-Type, If-None-Match, Cookie, Cookies, x-session-id, x-atg-host
Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Allow: POST
Cache-Control: private
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Date: Thu, 30 Jun 2016 16:39:48 GMT
Server: Microsoft-IIS/7.5
Set-Cookie: ASP.NET_SessionId=p5aolcjpwd0qfhqjdbluha1h; path=/; HttpOnly
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
The method is still not allowed. I get "405 method not allowed".
I think it is because the "Access-Control-Allow-Headers" is sending me types and the "Content-Type" case is not matched.
The client and the server is running on HTTPS.
Any insights?
angular version: 1.5.7
Update
The web service developer followed this guide to enable CORS on the server and it worked.
http://enable-cors.org/server_wcf.html
From the above answer and the URL mentioned
http://enable-cors.org/server_wcf.html
Create Message Inspector
public class CustomHeaderMessageInspector : IDispatchMessageInspector
{
Dictionary<string, string> requiredHeaders;
public CustomHeaderMessageInspector (Dictionary<string, string> headers)
{
requiredHeaders = headers ?? new Dictionary<string, string>();
}
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
foreach (var item in requiredHeaders)
{
httpHeader.Headers.Add(item.Key, item.Value);
}
}
}
Create Endpoint Behavior and use Message Inspector to add headers
public class EnableCrossOriginResourceSharingBehavior : BehaviorExtensionElement, IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
var requiredHeaders = new Dictionary<string, string>();
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
}
public void Validate(ServiceEndpoint endpoint)
{
}
public override Type BehaviorType
{
get { return typeof(EnableCrossOriginResourceSharingBehavior); }
}
protected override object CreateBehavior()
{
return new EnableCrossOriginResourceSharingBehavior();
}
}
Register new behavior in web.config
<extensions>
<behaviorExtensions>
<add name="crossOriginResourceSharingBehavior" type="Services.Behaviours.EnableCrossOriginResourceSharingBehavior, Services, Version=1.0.0.0, Culture=neutral" />
</behaviorExtensions>
</extensions>
Add new behavior to endpoint behavior configuration
<endpointBehaviors>
<behavior name="jsonBehavior">
<webHttp />
<crossOriginResourceSharingBehavior />
</behavior>
</endpointBehaviors>
Configure endpoint
<endpoint address="api" binding="webHttpBinding" behaviorConfiguration="jsonBehavior" contract="Service.IServiceContract" />

Can't set or override on specific header using Angular.js $http

I'm using Angular.js 1.4.8 and Fiddler 4 for debugging my requests.
The following is the request I made using AngularJS $http.
var postRequest = {
method: 'POST',
url: 'https://speech.platform.bing.com/recognize',
headers: {
'Transfer-Encoding': 'chunked',
Expect: '100-continue',
Expect2: 'abc',
Accept: 'application/json;text/xml',
Host: 'region.platform.bing.com',
'Content-Type': 'audio/wav; samplerate=8000',
Authorization: 'auth-token',
'Accept-Language': undefined,
'Accept-Encoding': undefined,
'User-Agent': undefined,
},
params: {
scenarios: 'smd', // 'smd' in the internal sample code,
locale: langString,
'device.os': 'wp7',
version: '3.0',
format: 'json',
},
data: "test"
};
$http(postRequest).then(function (response) {
console.log(response)
});
However, as described in below, in the actual request, there are some missing headers (e.g., Expect, Transfer-Encoding). In addition, there are still automatically added headers by Angular even after I set it as undefined (as guided in official document: https://code.angularjs.org/1.4.8/docs/api/ng/service/$http).
POST https://speech.platform.bing.com/recognize?device.os=wp7&format=json&locale=en-US&scenarios=smd&version=3.0 HTTP/1.1
Expect2: abc
Accept: application/json;text/xml
Content-Type: audio/wav; samplerate=8000
Authorization: 'auth-token'
**Accept-Language: en-US,en;q=0.8,ko;q=0.6,zh-Hans-CN;q=0.4,zh-Hans;q=0.2
Accept-Encoding: gzip, deflate**
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; MSAppHost/3.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240
Host: speech.platform.bing.com
Content-Length: 271491 Connection: Keep-Alive Cache-Control: no-cache
Cookie: MUIDB=39DE0AD21AD46AF2039D02BB1BB26B61
Is there any ways that
Can I add headers which I could not add using 'headers' objects, and
Can I remove the headers automatically added by Angular?
Or is it the Angular bug?
Yes you can. You can use angular interceptor to handle it globally. So for each request, you can automatically remove the unwanted headers and add necessary headers.
$httpProvider.interceptors.push(['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
return {
request: function (config) {
config.headers = config.headers || {};
var authData = localStorageService.get('authData');
if (authData) {
config.headers.Authorization = 'Bearer ' + authData.token;
}
return config;
},
response: function (result) {
return result;
},
responseError: function (rejection) {
console.log('Failed with', rejection.status, 'status');
if (rejection.status == 401) {
localStorageService.remove('authData');
window.location.replace(window.location.origin)
}
if (rejection.status == 307) {
$location.url('/SessionExpired');
}
if (rejection.status == 403) {
$location.url('/Forbidden');
}
if (rejection.status == 500) {
$location.url('/InternalServerError');
}
return $q.reject(rejection);
}
}
}])
Setting HTTP Headers
module.run(function($http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
});
Beware, other answers can be misleading ... Yes, using the suggested strategies, you can override some headers but not all! ... The reason of this is that, by specification, some headers are reserved and will be controlled only by the browser ... Examples of these reserved headers are:
Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
...
You can find more information about this in the following urls:
AngularJS: Refused to set unsafe header “Access-Control-Request-Headers”
Forbidden Header name for use with XMLHttpRequest

$http angular pass object?

Hello how can i pass this object as param in Http with angular?
Because my wcg public void CreateNewAccount(Users us)
$scope.RegisterUser = function(){
var us = {
UserName:$scope.userName,
Password:$scope.password,
UserRoleID:null,
Company:$scope.company,
Terms:$scope.terms,
ID:null,
BuyerID:app.buyerId
};
$http.get(
app.wcf+'/CreateNewAccount'angular.toJson({us:us}))
.then(
function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};
You need to pass your object as params in to the config of the $http.get(url, config) method.
$http.get(app.wcf + '/CreateNewAccount', {params: us})
.then(function(resp){
app.Logger(resp.data);
},
function(err){
app.Logger(err);
})};
That said, you shouldn't be passing this data as a GET request, especially not with a username and password in the query string.
For get, you should use params:
$http({method:'GET', url:'url', params:us})
I'm getting this it seams to call OPTIONS
Remote Address:192.168.58.182:80
Request URL:http://192.168.58.182/ESService/ESService.svc/CreateNewAccount
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,pl;q=0.6
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:192.168.58.182
Origin:http://localhost:8100
Referer:http://localhost:8100/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36
Response Headersview source
Access-Control-Allow-Headers:Content-Type, Accept
Access-Control-Allow-Methods:POST,GET,OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1728000
Allow:POST
Content-Length:1565
Content-Type:text/html; charset=UTF-8
Date:Fri, 30 Jan 2015 14:10:34 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET

Jquery File Upload - Not sending headers in IE9

I'm using jQuery Fileupload to upload files. Its not sending headers that I set to the server. Why is the Authorization header missing only in IE but passed in chrome?
Here is the code:
upload_photo: function(){
var url = '/api/v1/upload';
$('#photoupload').fileupload({
url: url,
dataType: 'json',
paramName: 'uploadFile',
beforeSend: function ( xhr ) {
setHeader(xhr);
$("#check_progress").html('true');
},
done: function (e, responseJSON) {
var id = responseJSON.result.id;
url = responseJSON.result.url;
var photo_ids = $("#photo_ids");
var val = photo_ids.val();
photo_ids.val(val + id.toString() + ",");
$(".photothumb-wapper").append('<div class=\"photothumb\" id="post_photo_'+id+'"><div><img src=\"'+url+'\" /></div><img class=\"thumb-delete photo_delete\" id=\"'+id+'\" title=\"Remove\" src=\"/assets/delete-red.png\"></div>');
$("#check_progress").html("");
},
start: function (e, data) {
$(".photothumb-wapper").append('<div class="photothumb photoprogress" style="border:none"><img src="/assets/ajax-loader.gif" /></div>');
},
always: function (e, data) {
$(".photoprogress").remove();
}
});
}
var setHeader = function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7');
};
Headers passed in IE:
Request : POST /api/v1/upload HTTP/1.1
Accept : text/html, application/xhtml+xml, \*/\*
Referer : url
Accept-Language : en-US
User-Agent :Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Content-Type :multipart/form-data; boundary=---------------------------7de2dfe037204f6
Accept-Encoding :gzip, deflate
Host :url
Content-Length :776595
DNT :1
Connection :Keep-Alive
Cache-Control :no-cache
Cookie :sitecookies
Headers passed in Chrome:
ResponseHeaders
date : Tue, 04 Mar 2014 07:32:20 GMT
Connection: Keep-Alive
content-length:225
content-type:application/json; charset=utf-8
cache-control:no-cache
RequestHeaders
Accept: application/json, text/javascript, \*/\*; q=0.01
Authorization: Bearer fdf49c4f1cfgc176eb952f18eeefaec3e7
X-Requested-With: XMLHttpRequest
Why is the Authorization header missing in IE?
This answers my question,
Only browsers with support for XHR file upload support setting custom headers.
As a workaround in old browsers like our dear IE, you could set a cookie with the authentication token when the user authenticate and then get it in the server and verify it the same way you verify the header one. I know that it is not the most elegant solution but it works.

Angular $http.post not sending any data

I'm super stuck with trying to simply post JSON data but for some reason it won't work.
angular.module('pocket.controllers', [])
.controller('ArticleList', function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})
When I inspect the request in the Chrome inspector it doesn't seem like any data is actually being posted:
Request URL:https://getpocket.com/v3/oauth/request
Request Method:OPTIONS
Status Code:400 Bad Request
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:accept, origin, x-requested-with, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:getpocket.com
Origin:http://pocket.dev:8000
Pragma:no-cache
Referer:http://pocket.dev:8000/app/index.html
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36
Response Headersview source
Cache-Control:private
Connection:keep-alive
Content-Length:15
Content-Type:text/html; charset=UTF-8
Date:Wed, 24 Jul 2013 17:18:04 GMT
P3P:policyref="/w3c/p3p.xml", CP="ALL CURa ADMa DEVa OUR IND UNI COM NAV INT STA PRE"
Server:Apache/2.2.25 (Amazon)
Status:400 Bad Request
X-Error:Missing consumer key.
X-Error-Code:138
X-Powered-By:PHP/5.3.27
X-Source:Pocket
As you can see, the X-Error is "Missing consumer key" which implies the data is not being posted correctly.
Add this line to your code;
$http.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded";
Modified code will be like this;
angular.module('pocket.controllers', []) .controller('ArticleList',
function($scope, $http) {
$scope.signIn = function() {
var postObject = new Object();
postObject.consumer_key = pocketKey;
postObject.redirect_uri = "http://www.example.com";
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post(apiUrl, postObject).success(function(data){
alert(data);
});
}
})

Categories

Resources