Why the "Authorization" field in Http Headers in Alamofire set automatically? - ios

I want to send my apiKey in headers in Alamofire to my web service.But no matter how many times I test it,I still cant to get the value of apiKey in my web service.
My web service always return this error,cause cant get the apiKey in the header.
{
"error": true,
"message": "Api key is missing"
}
This is how I make the request,I think I didnt do anything wrong,but the web service still cant get the value of apiKey.
let My_URL = "My_url"
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
Alamofire.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}
My web service currently is serving for Android and Web version.Both running well,but I really no idea why the ApiKey in headers cant get it from webservice.
Totally no idea what is going wrong..Somebody please help!!!!
EDIT
I attach the result from debugPrint here,please take a look and let me know what is the problem,I suspect the problem is cause by the "Authorization" tag in the result below,the "Authorization" field is not the field I set,and the value as well,is not the value I want as well.
But why is this happen?? And how to solve this problem?
[Response]: <NSHTTPURLResponse: 0x60c00003d4c0> { URL: http://My_URL} { Status Code: 400, Headers {
"Access-Control-Allow-Headers" = (
Authorization
);
"Access-Control-Allow-Methods" = (
"GET, POST, PUT, DELETE, OPTIONS"
);
"Access-Control-Allow-Origin" = (
"*"
);
Authorization = ( // <--why this authorization appear
16ebe49c51039ddfbb09e5df8519e755 //this is not the value I set
);
Connection = (
close
);
"Content-Length" = (
45
);
"Content-Type" = (
"application/json"
);
Date = (
"Sun, 14 Dec 2017 14:20:59 GMT"
);
Server = (
"Apach(Ubuntu)"
);
"X-Powered-By" = (
"PHP/5.5.9-1"
);
} }
EDIT:
To solve the problem above,I read this following question
iOS Alamofire Incorrect Authorization Header
How to disable the URLCache completely with Alamofire
Therefore,I modify my request as below,but the problem still the same,the result of debugPrint is still same as above.
let configuration = URLSessionConfiguration.default
configuration.urlCache = nil
let sessionManager = Alamofire.SessionManager(configuration: configuration)
let params : [String : Any]=["param1":value1,"param2":value2]
let headers : HTTPHeaders = [
"Content-Type":"application/x-www-form-urlencoded",
"authorization" : apiKey //<--this is the value I need to
get in header of web service
]
sessionManager.request(MY_URL,method: .post ,parameters : params ,headers:headers).responseJSON {
response in
debugPrint(response)
}.session.finishTasksAndInvalidate()

I know this question was asked long time ago, but to solving other persons issue I answer it.
Removing Authorization header value is not a bug make by alamofire lib. This key and some other keys are NSURLSession reserved key, so according to apple document value of these keys may change. To avoid this issue you must change the header name to something like Authorization-App or any other key confirmed by your API team.

Related

How to POST the json payload data inside a telegram chat using the bot API?

I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=#alerttest&text=1111"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
"stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
}
""""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
   
You are probably confused about the working of HTTP methods and Telegram API methods.
First step: Telegram sendMessage works with POST HTTP method.
It requires the text parameter, passed as GET parameter: otherwise you'll send an empty message.
This means, that if you're willing to include the JSON payload as text message you have to include your JSON attribute's values into the Telegram sendMessage text parameter, otherwise you won't be able to see that into the final message.
I found the following issues with the given code:
url contains a space.
chat_id value should be numeric. Use https://web.telegram.org/ to get the chat_id from the URL. It should be a negative number. If it's a channel or supergroup, you should prepend 100 after the minus sign.
&text=1111 should be removed from the URL, as text is specified in the body when using the requests.post() method.
data should be a dictionary containing key name text.
You can not specify "Content-Type": "application/json" in headers unless your data dictionary has been transcoded to json. This can be solved in the requests.post() call by either changing data= to json=, or by not specifying headers at all.
Working:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, headers=headers, json=data)
print(resp.status_code)
Working:
import requests
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, data=data)
print(resp.status_code)

Can't create account in aqueduct's db_and_auth/wildfire example

I have been trying to learn how to use Aqueduct's authorization but I am struggling with some errors.
I found this question (OAuth Error using Aqueduct, mismatched ManagedPropertyType), which solved the first error saying it was expecting a string while an _ImmutableList was being passed. Nevertheless, whenever I make a the following POST request:
Future main() async {
var http2 = new http.Client();
var clientID = "com.wildfire.mobile";
var clientSecret = "myspecialsecret ";
var body = "username=usr&password=pwd&grant_type=password";
var clientCredentials = new Base64Encoder().convert(
"$clientID:$clientSecret".codeUnits);
var response = await
http.post(
"http://localhost:8081/register",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic $clientCredentials"
},
body: body);
I get a 500 error as a response and the following exception:
NoSuchMethodError: The getter 'credentials' was called on null.
in
request.authorization.credentials.username
Nevertheless, in the _user table I see an entry for the user I registered. Should I juts ignore the error or is there someway to solve this issue?
Edit:
It was indeed a misconfiguration issue. After deleting all my databases, I added a database.yaml file, which I thought was the same as the config.yaml but apparently is not.
Credentials will be null if the request doesn't pass through an Authorizer. In this case, you'll want a basic authorizer:
router
.route("/register")
.pipe(new Authorizer.basic(authServer))
.generate(() => new RegisterController());

Search for Twitter handles using Google Apps Script and Twitter API - doesn't work

I'm trying to find Twitter handles from a spreadsheet containing names of people.
I can't get it work with this request, which I believe is the one I should be using as I only have peoples names (e.g. Adam Smith): api.twitter.com/1.1/users/search.json?q=
I get the following error:
Request failed for api.twitter.com/1.1/users/search.json?q=Name returned code 403. Truncated server response: {"errors":[{"message":"Your credentials do not allow access to this resource","code":220}]} (use muteHttpExceptions option to examine full response) (line 38).'
I've tried searching this error but that hasn't helped me so far.
If I use, for example, this request, it works: api.twitter.com/1.1/users/show.json?screen_name=
So I can get the screen_name back in the spreadsheet, but that's pointless obviously because it needs the screen name to work in the first place...
The whole thing is based on this work, all the requests in that code work for me. It's just this search request that doesn't work. What's going wrong?
var CONSUMER_KEY = 'x';
var CONSUMER_SECRET = 'x';
function getTwitterHandles(name) {
// Encode consumer key and secret
var tokenUrl = "https://api.twitter.com/oauth2/token";
var tokenCredential = Utilities.base64EncodeWebSafe(
CONSUMER_KEY + ":" + CONSUMER_SECRET);
// Obtain a bearer token with HTTP POST request
var tokenOptions = {
headers : {
Authorization: "Basic " + tokenCredential,
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
method: "post",
payload: "grant_type=client_credentials"
};
var responseToken = UrlFetchApp.fetch(tokenUrl, tokenOptions);
var parsedToken = JSON.parse(responseToken);
var token = parsedToken.access_token;
// Authenticate Twitter API requests with the bearer token
var apiUrl = 'https://api.twitter.com/1.1/users/search.json?q=screen_name='+name;
var apiOptions = {
headers : {
Authorization: 'Bearer ' + token
},
"method" : "get"
};
var responseApi = UrlFetchApp.fetch(apiUrl, apiOptions);
var result = "";
if (responseApi.getResponseCode() == 200) {
// Parse the JSON encoded Twitter API response
var tweets = JSON.parse(responseApi.getContentText());
return tweets.id
}
Logger.log(result);
}
Edit: deleted the https a few times because of the URL limit
You can not search for users using application-only authentication (bearer token). See https://dev.twitter.com/oauth/application-only. A user context (access token) is needed for that request. You can get your own access token from https://apps.twitter.com.

403 Response From Adobe Experience Manager OAuth 2 Token Endpoint

I am using Postman to test OAuth 2 from a vanilla AEM install.
Postman can successfully obtain the authorization code from /oauth/authorize after I grant access:
But when it tries to use the code to obtain a token from /oauth/token it receives the following response:
HTTP ERROR: 403 Problem accessing /oauth/token. Reason: Forbidden
Powered by Jetty://
Looking in Fiddler it is doing a POST to /oauth/token with the following Name/Values in the body:
client_id: Client ID from /libs/granite/oauth/content/client.html
client_secret:
Client Secret from /libs/granite/oauth/content/client.html
redirect_uri: https://www.getpostman.com/oauth2/callback
grant_type: authorization_code
code: Code returned from previous request to oauth/authorize
Am I missing something?
Would help if you can list some code snippets on how you are building the url and fetching the token.
Here's an example of how we've implemented very similar to what you are trying to do, maybe it'll help.
Define a service like below (snippet) and define the values (host, url, etc) in OSGI (or you can also hard code them for testing purposes)
#Service(value = OauthAuthentication.class)
#Component(immediate = true, label = "My Oauth Authentication", description = "My Oauth Authentication", policy = ConfigurationPolicy.REQUIRE, metatype = true)
#Properties({
#Property(name = Constants.SERVICE_VENDOR, value = "ABC"),
#Property(name = "service.oauth.host", value = "", label = "Oauth Host", description = "Oauth Athentication Server"),
#Property(name = "service.oauth.url", value = "/service/oauth/token", label = "Oauth URL", description = "Oauth Authentication URL relative to the host"),
#Property(name = "service.oauth.clientid", value = "", label = "Oauth Client ID", description = "Oauth client ID to use in the authentication procedure"),
#Property(name = "service.oauth.clientsecret", value = "", label = "Oauth Client Secret", description = "Oauth client secret to use in the authentication procedure"),
#Property(name = "service.oauth.granttype", value = "", label = "Oauth Grant Type", description = "Oauth grant type") })
public class OauthAuthentication {
...
#Activate
private void activate(ComponentContext context) {
Dictionary<String, Object> properties = context.getProperties();
host = OsgiUtil.toString(properties, PROPERTY_SERVICE_OAUTH_HOST,new String());
// Similarly get all values
url =
clientID =
clientSecret =
grantType =
authType = "Basic" + " "+ Base64.encode(new String(clientID + ":" + clientSecret));
}
public static void getAuthorizationToken(
try {
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
Session session = resourceResolver.adaptTo(Session.class);
// Getting the current user
Authorizable auth = userManager.getAuthorizable(session.getUserID());
user = auth.getID();
password = ...
...
...
String serviceURL = (host.startsWith("http") ? "": protocol + "://") + host + url;
httpclient = HttpClients.custom().build();
HttpPost httppost = new HttpPost(serviceURL);
// set params
ArrayList<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
formparams.add(new BasicNameValuePair("username", user));
formparams.add(new BasicNameValuePair("password", password));
formparams.add(new BasicNameValuePair("client_id", clientID));
formparams.add(new BasicNameValuePair("client_secret",clientSecret));
formparams.add(new BasicNameValuePair("grant_type",grantType));
UrlEncodedFormEntity postEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(postEntity);
// set header
httppost.addHeader("Authorization", authType);
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (response.getStatusLine().getStatusCode() == 200) {
if (entity != null) {
object = new JSONObject(EntityUtils.toString(entity));
}
if (object != null) {
accessToken = object.getString("access_token");
////
}
}
}
I found the answer myself and thought I'd share the process I went through as well as the answer because it might help other people new to AEM.
How to find the cause of the error:
Go to CRXDE Lite.
Select console.
Then deselect the stop button to allow new console logs to appear (this is very counter-intuitive to me).
From here I was able to see the cause of the issue:
org.apache.sling.security.impl.ReferrerFilter Rejected empty referrer header for POST request to /oauth/token
Because postman does not place a referrer in the request header I had to tell Apache Sling to allow empty request headers.
To do this:
Go to /system/console/configMgr
Open the Apache Sling Referrer Filter Config
Select the Allow Empty check box
Good way to allow this to list the allowed hosts, otherwise this is against best practices for AEM security checklist.
Its fine for development environment not for production.

Delete entry from database with WinJS and OData

I'm trying to delete an entry from the database by odata. I get the error message
{"error":{"code":"","message":{"lang":"en-US","value":"Bad Request - Error in query syntax."}}}
my code:
function deleteMonthEntry() {
var item = actMonthEntries.getItem(listIndex);
var queryString = "Stundens(" + item.data.datensatz_id + ")?$format=json";
var requestUrl = serviceUrl + queryString;
WinJS.xhr({
type: "delete",
url: requestUrl,
headers: {
"Content-type": "application/json"
}
}).done(
function complete(response) {
},
function (error) {
console.log(error);
}
);
}
My request URL looks like this:
requestUrl = "http://localhost:51893/TimeSheetWebservice.svc/Stundens(305233)?$format=json"
Thanks
Marlowe
At least I found the solution:
I've entered an filter request to my service like this:
TimeSheetWebservice.svc/Stundens?$filter=datensatz_id eq 305221
this returned the correct entry with this link:
TimeSheetWebservice.svc/Stundens(305221M)
So if I enter a M after the ID, everything works fin. But I have no idea where this M comes from.
Can anyone tell me the reason for this M? It does not belong to the ID. The ID is this
305221
Marlowe
Are you sure the server you're talking to supports the $format query option? Many don't. I would try removing that part of the request URI, and instead modify your headers value to specify an Accept header:
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
For servers where $format is allowed, giving it a json value is equivalent to providing an Accept header with the application/json MIME type.
In general, for a DELETE operation, the Accept header or $format value only matters for error cases. With a successful DELETE, the response payload body will be empty, so there's no need for the server to know about your format preference.

Resources