Could not decode token: The token ### - json

I'm using Laravel 5.3 as an API for my iOS app. When I try to make HTTP calls with headers and parameters I get this 401 error:
message = "Could not decode token: The token
\"Optional(\""eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6XC9cL2xvY2FsaG9zdDo4MDAwXC9hcGlcL2F1dGhcL3Bvc3RMb2dpbiIsImlhdCI6MTQ4MDUzNzQxOCwiZXhwIjoxNDgwNTQxMDE4LCJuYmYiOjE0ODA1Mzc0MTgsImp0aSI6ImMyZmYxNzI5N2U5OGU4MzkzYzZkZWRmNTZlN2ZkMzNkIn0.u6sQqlq5k-B5jhZ7EymkXLlcTIQ-i7X_83an5irwTss\"" is an
invalid JWS";
"status_code" = 401; }
This is the code that makes the HTTP request:
let headers = ["Authorization":"Bearer \(token)"]
request(url! , method: .get, parameters: nil, encoding: JSONEncoding.default , headers: headers )
.responseJSON { response in
print("RESPONSE \(response)")
I did some googling and found a package to encode JWT called JWTDecode.swift. Here is the link to the code: https://github.com/auth0/JWTDecode.swift. I still couldn't figure out how to solve this issue.

change
let headers = ["Authorization":"Bearer \(token)"]
to something like
guard let token = token else { return }
let headers = ["Authorization":"Bearer \(token)"]
otherwise you are sending Optional(<token>) instead of <token>.

Related

How to send json body in get request

I know sending json body in get request is violating http rules, however according to client's requirement the server is accepting json body in get request.so i want to send json body in my get request using alamofire.
i tried various parameter encoding types.nothing worked.
func listNews( withCompletionHandler:#escaping (_ status:Bool, _ message: String, _ yearLevels: JSON) -> Void){
let parameters = [
"month": "07",
"year": "2019",
"record_start": 0,
"record_offset": 100
] as [String : Any]
let headers = [
"Content-Type": "application/json"
]
let url = STAFF_SERVICE_URL+"staff/2/news?api_key=\(api_key)"
print("URL > \(url)")
Alamofire.request(url, method: .get,parameters:parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
let statusCode = response.response?.statusCode
print(statusCode ?? "Success Error Code")
if(statusCode==200){
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
withCompletionHandler(true,"Success",swiftyJsonVar)
}else if(statusCode==400){
withCompletionHandler(false,"System Error. Please try again later.",JSON.null)
}else{
withCompletionHandler(false,"System Error",JSON.null)
}
}
}
i expect array of json objects in response. but the actual output is time out error
Actually you should change encoding method for get request. You have set encoding: JSONEncoding.default. Instead of that, use encoding: URLEncoding.default.
Second thing, if you are sending parameters in json body, then send all parameters instead of some sending with body and some in url. So, your api_key=\(api_key) should be in json body.
I hope this will fix your issue.

Alamofire - POST request with JSON giving 301

I want to send POST request with JSON, I'm expecting JSON object with auth_token and refresh_token in response. My code looks like this:
let headers: HTTPHeaders = [
"Authorization": "Basic " + data.toBase64() //data is just string needed for authentication
]
// this should be a JSON
let parameters = [
"code": self.code,
"grant_type": "authorization_code",
"redirect_uri": "populi://callback"
]
Alamofire.request("https://populi.pl/api/v1/auth/token", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseString { response in
print(response.request)
print("\n3 RESPONSE : \(response)")
print("\n3 POST : \(response.response)")
print("\n3 DATA : \(response.data)")
print("\n3 RESPONSE RESULT : \(response.result)")
print("\n3 RESPONSE RESULT VALUE : \(response.result.value)")
print("3 ERROR : \(response.error)")
}
Yeah, I print a lot of things, that's because I'm new to networking.
In response I'm getting 301 moved permanently. Why? I have no idea what's wrong. Is this wrong JSON in parameters or maybe something with redirecting? I should get 200 and JSON in response.
try this
func getData(){
let todoEndpoint: String = Your url
let params: Parameters = [yor parameters]
let headers: [String : String] = [
"Content-Type": "application/x-www-form-urlencoded",
]
Alamofire.request(todoEndpoint, method: .post, parameters: params,headers: headers)
.responseJSON { response in
switch response.result {
case .success:
let json = JSON(response.result.value as Any)
print(json)
break
case .failure(let error):
print(error)
}
}
}
I solved this with "/" at the end of request URL.
I was using URLSession for requests and was getting 301 for 1 request
then I tried Alamofire and still got the same response and at the end, I figured out that issue was that I was not appending / at the end of endpoint

Alamofire 4.4 Serialization Failure, Content Type issue

I'm new to Alamofire, have been trying to work with a web service that I can use through Postman but I can't use via Alamofire. In Postman I can set HTTP Header Key "Accept" with "application/json" and I get a response in Content-Type →application/json; charset=utf-8.
However when I try to do the same using Alamofire, the serialization fails cause the response comes in xml.
Is there a solution for this? I tried custom HTTP Headers & defaulting session manager with the "Accept" key being set to "application/json" but I can't get the intended response! Here is a sample of the code.
if let url = URL(string: "http://madinaty.demoday.us/api/1/lookup/stable/") {
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = HTTPMethod.get.rawValue
urlRequest.addValue("application/json", forHTTPHeaderField: "content-type")
urlRequest.addValue("application/json", forHTTPHeaderField: "accept")
let request = Alamofire.request(urlRequest)
.responseJSON{ response in
print("Request: \(String(describing: response.request))") // original URL request
print("---------------------------")
print("HTTP URL response: \(String(describing: response.response))") // HTTP URL response
print("---------------------------")
print("Data: \(String(describing: response.data))") // server data
print("---------------------------")
print("Result of Reponse Serialization \(response.result)") // result of response serialization
print("---------------------------")
print("Error \(response.result.error)") // result of response serialization
print("---------------------------")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
This is the error I get:
Optional(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error
Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character
0." UserInfo={NSDebugDescription=Invalid value around character 0.})))
I also tried this:
let header = ["content-type" : "application/json"]
Alamofire.request("http://madinaty.demoday.us/api/1/lookup/stable/",
method: .get,
parameters: nil,
encoding: JSONEncoding.default,
headers: header).responseJSON {
response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response
}
Doesn't work either!
Neither did this work:
// get the default headers
var headers = Alamofire.SessionManager.defaultHTTPHeaders
// add your custom header
headers["Accept"] = "application/json"
// create a custom session configuration
let configuration = URLSessionConfiguration.default
// add the headers
configuration.httpAdditionalHeaders = headers
// create a session manager with the configuration
let sessionManager = Alamofire.SessionManager(configuration: configuration)
// make calls with the session manager
let request = sessionManager.request("http://madinaty.demoday.us/api/1/lookup/stable/")
.responseJSON { response in
debugPrint(response)
print("Result of Reponse Serialization \(response.result)")
}
debugPrint(request)
After hours of different trials, I finally found the solution for the problem
It turned out that just removing the trailing slash of the URL would solve the problem!
Try creating a custom session header configuration:
var headers = Alamofire.SessionManager.defaultHTTPHeaders
headers["content-type"] = "application/json"
// custom session configuration
let configuration = URLSessionConfiguration.default
configuration.httpAdditionalHeaders = headers
let sessionManager = Alamofire.SessionManager(configuration: configuration)
Then make your request using sessionManager.request(...) instead of Alamofire.request(...)

Alamofire using query parameters status 500

I'm calling an Api route to get branches of a local store using longitude, latitude & radius. The api route is working just fine on postman. Using Alamofire it is replying internal server error 500. I doubt the issue is in the parameters but i just tested everything and every combination with no success.
Here is my HTTP request:
let branchesRoute = "geo/services/"
//Get branches within location radius
func getBranchesWithRadius (serviceID: Int, location: CLLocation, completion: #escaping (_ status:Bool, _ error:Error?, _ msg:String?, _ branches:NSArray?) ->())
{
let route = URL(string:branchIp + branchesRoute + String(serviceID) + "/branches")
print(route)
let header: HTTPHeaders = [
"Content-Type":"application/json",
"auth-token": Helper.shared.getApiKey()//"\(Helper.shared.getApiKey())"
]
let params: Parameters = [
"longitude" : location.coordinate.longitude,
"latitude" : location.coordinate.latitude,
"radius" : Helper.shared.getRadius()
]
print(params)
Alamofire.request(route!, method: .get, parameters: params, encoding: JSONEncoding.default, headers: header)
.validate(statusCode: 200..<300)
.responseJSON { (response) in
switch response.result {
case .success( _):
let json = response.result.value!
// let swiftyJson = JSON(json)
completion(true, nil, nil, json as? NSArray)
// print(json)
case .failure(let err):
print(err)
if response.response?.statusCode == 401 {
completion(false,err,"Unauthorized",nil)
} else {
completion(false, err, "Error getting branches",nil)
}
}
}
}
This is the route im calling from postman:
http://100.100.70.185:9090/geo/services/3/branches?longitude=31.331358000000002&latitude=30.082763&radius=1000000
When i used print() command in swift these were my results:
print(params) = ["longitude": 31.331358000000002, "latitude": 30.082763, "radius": 100000]
print(route) =
Optional(http://100.100.70.185:9090/geo/services/3/branches)
Regarding the Optional i'm just unwrapping it route!
Regarding the ip address i wrote here are not the real ones that i use in case you tested and it didn't work out.
The actual issue is in encoding and you have to use the correct ParameterEncoding depending on your API implementation.
Use URLEncoding if the Content-Type HTTP header field of an encoded request with HTTP body is set to application/x-www-form-urlencoded; charset=utf-8
-
Use JSONEncoding if the Content-Type HTTP header field of an
encoded request is set to application/json
-
Use PropertyListEncoding if the Content-Type HTTP header field of
an encoded request is set to application/x-plist

Get Request Status code: 400 Swift

i got code error **status code: 400*
URL: https://conversation.8villages.com/1.0/contents/articles?state=published }
{ status code: 400, headers {
Connection = "keep-alive";
"Content-Length" = 2;
"Content-Type" = "application/json";
Date = "Tue, 11 Apr 2017 07:49:13 GMT";
Server = nginx;
} }
2 bytes
SUCCESS
JSON: {
}
my json is result SUCCESS but wht not show my DATA?
actually i get request method Alamofire with Consumer Key, Consumer Secret, Token Key and Token Secret. like this :
let params: HTTPHeaders = ["oauth_consumer_key":"*****",
"oauth_consumer_secret":"*****",
"oauth_token_key":"*****.",
"oauth_token_secret": "*****",
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp_key" : "1491366048",
"oauth_version": "1.0"] as [String : Any] as! HTTPHeaders;
Alamofire.request("https://conversation.8villages.com/1.0/contents/articles?state=published", method: .get, headers: params).responseJSON { response in
print("test", response.request!) // original URL request
print("ini responseny", response.response!) // HTTP URL response
print("test", response.data!) // server data
print("test", response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
how to get my data API ??
Please keep in mind :
400 Bad Request : The server cannot or will not process the request
due to something that is perceived to be a client error (e.g.,
malformed request syntax, invalid request message framing, or
deceptive request routing).
For a better understanding check : this