Is anyone knows how Flutter URI encoding/decoding works? - flutter

Is anyone knows how Flutter URI encoding/decoding works?
I have one issue. Let me give you some background on the issue. We have one deep link which will give us the email and access token code to reset the password. We will validate the token on the front end and then allow users to do a reset.
Here is the sample URL from Firebase dynamic link
https://example.com/auth/resetPassword/?access_token=abcd&email=test+abc#xyz.com
Firebase dynamic link will give us this URL in the URI object. The issue is when I try to fetch the query params from this URI object, it removes plus sign from an email and replaces it with the space character instead. E-mail should same as displayed in the above link. This is the email received when I fetch query params: test abc#xyz.com
I have created two dart pads to figure out the issue. Here is the 1st sample where I am parsing (since firebase dynamic link is doing the same) the URL into the URI object and tried printing the output. As expected it removes the plus sign.
Code:
main() {
var httpsUri = Uri.parse("https://example.com/auth/resetPassword/?access_token=abcd&email=test+abc#xyz.com");
print(httpsUri.queryParameters);
}
Output:
{access_token: abcd, email: test abc#xyz.com}
In another sample, I tried creating the URI object from the same parameters and link but manually. Here is the code
Code:
main() {
var httpsUri = Uri(
scheme: 'https',
host: 'example.com',
path: '/auth/resetPassword/',
queryParameters: {
'access_token': 'abcd',
'email': 'test+abc#xyz.com'
});
print(httpsUri.queryParameters);
}
Output:
{access_token: abcd, email: test+abc#xyz.com}
If you see here, the email is correctly displayed.
My exact scenario is matching with the first sample code. Based on my findings it removes the plus sign due to encoding and decoding of the URL as a plus sign has a special meaning in the URL. But on the other hand why it is not happening in 2nd example?
Any help would be appreciated!

+ is a reserved character for URIs and therefore should be encoded to %2B if you want a literal + character.
But on the other hand why it is not happening in 2nd example?
Your second example works because it constructs a Uri object directly, and if you were to convert it to a String, it would perform necessary encodings for you. That is, print(httpsUri) would output:
https://example.com/auth/resetPassword/?access_token=abcd&email=test%2Babc%40xyz.com
rather than original (malformed) URL:
https://example.com/auth/resetPassword/?access_token=abcd&email=test+abc#xyz.com

Related

Spotify API demanding a parameter that is not required

I know this is a particular issue that I'm having but I'm struggling with it for ages...If anyone could give me a hint on how to proceed It would be great.
I'm trying to integrate my flutter app to Spotify API and according to Spotify docs, after the user accepted the conditions at their site, it would be redirected back with a code - In my application I'm already retrieving this code. After that, I need to make a request for another endpoint to "trade" my code for an auth.
The docs demand a POST with 3 parameters(grant_type,redirect_uri and code). But even though I send all of this informations I get a (400 -Bad Request) with the description:
{"error":"invalid_request","error_description":"code_verifier
required"}
But note that code_verifier is only required for a PKCE request, as far as I understand.
My post method is the following:
Future getUserAccessToken(String authorizationCode) async {
// Get the Access Token in exchange for the Authorization Code
var url = 'https://accounts.spotify.com/api/token';
var body = {
'grant_type': 'authorization_code',
'code': authorizationCode,
'redirect_uri': redirectUrl,
};
var response = await post(Uri.parse(url), body: body, headers: {
'Content-Type': "application/x-www-form-urlencoded",
'Authorization':
'Basic ${base64Encode(utf8.encode('$clientID:$clientSecret'))}',
});
}
They also demand this at the authorization header:
Base 64 encoded string that contains the client ID and client secret key. The field must have the format: Authorization: Basic
I would recommend going forward with PKCE. It will protect your app against CSRF and authorization code injection attacks. It's also not too bad to implement.
All you should have to do is:
Generate a random string using the characters A-Z, a-z, 0-9, and the punctuation characters -._~ (hyphen, period, underscore, and tilde), between 43 and 128 characters long. This is your code_verifier
Hash that string with SHA256. This is your code_challenge.
Send those values in the requests as the documentation indicates, which means base64 url encoding them, as well. The Spotify doc says "The body of this POST request must contain the following parameters encoded in application/x-www-form-urlencoded".
Also, in case you haven't seen it, there's a OAuth flow example implemented in JS here: https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js Their copy of this portion looks like:
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code'
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
};
request.post(authOptions, function(error, response, body) {...})
The example has "request": "~2.83.0" in the package.json.
Notice how they use form which I would assume is base 64 url encoding the body, as the docs indicate. Not sure how the post method you're using with dart/flutter works with respect to base 64 url encoding, so that's something to investigate, as well.
Credit to https://www.oauth.com/oauth2-servers/pkce/authorization-request/ for providing some of the text in this response

Invalid_request_parameter (create and sending envelopes)

I'm trying to use a service of DocuSign API in an abap project. I want to send a document to a specific email so it can be signed. But im getting the following error:
"errorCode": "INVALID_REQUEST_PARAMETER",## "message": "The request contained at least one invalid parameter. Query parameter 'from_date' must be set to a valid DateTime, or 'envelope_ids' or 'transaction_ids' must be specified.
I tried the following:
CALL METHOD cl_http_client=>create_by_url
EXPORTING
url = l_url (https://demo.docusign.net/restapi/v2/accounts/XXXXXX')
proxy_host = co_proxy_host
proxy_service = co_proxy_service
IMPORTING
client = lo_http_client
lo_http_client->request->set_method( method = 'POST').
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'Accept'
value = 'application/json'.
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'X-DocuSign-Authentication'
value = get_auth_header( ). (json auth header)
CALL METHOD lo_http_client->request->set_cdata
EXPORTING
data = create_body( ).
This is my body:
CONCATENATE
`{`
`"emailSubject": "DocuSign REST API Quickstart Sample",`
`"emailBlurb": "Shows how to create and send an envelope from a document.",`
`"recipients": {`
`"signers": [{`
`"email": "test#email",`
`"name": "test",`
`"recipientId": "1",`
`"routingOrder": "1"`
`}]`
`},`
`"documents": [{`
`"documentId": "1",`
`"name": "test.pdf",`
`"documentBase64":` `"` l_encoded_doc `"`
`}],`
`"status": "sent"`
`}` INTO re_data.
The api request to get the Baseurl is working fine. (I know the error is quite specific what the problem is, but i cant find any sources on the docusign api documentation that one of the mentioned parameters should be added to the request)
Thank you in regards
The error message seems to indicate that you're Posting to an endpoint that requires certain query string parameters -- but you're not specifying them as expected in the query string. I'd suggest you check the DocuSign API documentation for the operation you are using, to determine what query string parameters it requires, and then ensure that you're including those parameters in your request URL.
If you can't figure this out using the documentation, then I'd suggest that you update your post to clarify exactly what URL (endpoint) you are using for the request, including any querystring parameters you're specifying in the URL. You can put fake values for things like Account ID, of course -- we just need to see the endpoint you are calling, and what qs params you're sending.
To create an envelope, use
https://demo.docusign.net/restapi/v2/accounts/XXXXXX/envelopes
instead of
https://demo.docusign.net/restapi/v2/accounts/XXXXXX
Thank you for all the answers, i found the mistake. Creating the request wasn´t the problem. I was using the wrong "sending"-method -_-.
now its working :)
lo_rest_client->post( EXPORTING io_entity = lo_request_entity ).

How do I add a field for a header for an authentication token for Swagger UI?

My team has just started creating RESTful services for data that has previously been handled by a large monolithic legacy application. We want to document the api with Swagger UI and I have set up with one problem.
I need to pass a SAML token as a header parameter, otherwise when we try to click on the "Try it out!" button I get a 401 Authentication error. How do I add a field to the Swagger UI so that someone can put a String for a SAML token to be sent in the request?
This is actually really easy. I saw references to the answer in the documentation but I didn't really understand what it was saying. There is a field at the top next to where your service URL goes and you can use that field to input a string to pass as a header value. That input field has an id of #input_apiKey.
Then in the index.html file you just add a line to the addApiKeyAuthorization() javascript function telling it to take the value of that field and pass it as whatever value you need.
Example:
function addApiKeyAuthorization(){
var key = $('#input_apiKey')[0].value;
if(key && key.trim() != "") {
swaggerUi.api.clientAuthorizations.add("samlToken", new SwaggerClient.ApiKeyAuthorization("samlToken", key, "header"));
swaggerUi.api.clientAuthorizations.add("Content-Type", new SwaggerClient.ApiKeyAuthorization("Content-Type", "application/json", "header"));
swaggerUi.api.clientAuthorizations.add("Accept", new SwaggerClient.ApiKeyAuthorization("Accept", "application/json", "header"));
}
}
$('#input_apiKey').change(addApiKeyAuthorization);
This sets the Content-Type and Accept headers to the same values for every request, and takes the value in that input field at the top of the page in the green header and sets it as my SAML token. So now if I paste in a valid SAML string my request works and I get data back!

Groovy REST URL mapping containing forward slashes

I have a REST service in Groovy on Grails; basic service that takes data and transforms it. It works fine except when the data being passed in has forward or back slashes. In those cases the browser tries to navigate to a directory based on the data:
localhost/traverse/map/321 64 fourth <<< this works fine
localhost/traverse/map/321/64/fourth <<< tries to find localhost/traverse/map/321/64/fourth and throws an http status 404
My urlmapping:
"map/$id" (controller: "map", action: "transform", formats=['text/plain'], method: "GET")
My controller. aside from the class declaration and class import nothing else going on:
def transform = {
//println params.id
if (param.id) {
DataMap dm = new DataMap();
render dm.hostNodeLookup(params.id)
}
}
Most of the data that will be passed to the REST service will have slashes and the number of slashes per "data being passed in" will vary from 1-N but I haven't been able to figure out how to escape/parse/other wise get around that issue. I've read up on this site but I didn't find it too helpful for this problem.
I do not have access to the web server to adjust encoding or how browsers render URL mappings and strings. The data doesn't get to the controller so I haven't been able to parse out the strings there. Anyone have ideas?
After reading this post I tried it and it worked like a charm.
In the urlmapping file I added this ** to the id variable:
"map/$id**" (controller: "map", action: "transform", formats=['text/plain'], method: "GET")

Linkedin API oAuth 2.0 REST Query parameters

I'm running into a problem with adding a query to the callback URL. I'm getting an invalid URI scheme error attempting to authorize the following string:
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75df1ocpxohk88&scope=rw_groups%20w_messages%20r_basicprofile%20r_contactinfo%20r_network&state=7a6c697d357e4921aeb1ba3793d7af5a&redirect_uri=http://marktest.clubexpress.com/basic_modules/club_admin/website/auth_callback.aspx?type=linkedin
I've read some conflicting information in forum posts here. Some say that it's possible to add query strings to callbacks, and others say that it results in error.
If I remove ?type=linkedin, I can authorize just fine and receive the token. It would make my life so much easier if I could use a query string on the callback url, as I need to do some additional processing in the callback.
In short, can I append a query string to the end of the callback url?
For fun, I tried encoding the callback url in the request (obviously this is a no-no according to their documentation):
https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=75df1ocpxohk88&scope=rw_groups%20w_messages%20r_basicprofile%20r_contactinfo%20r_network&state=5cabef71d89149d48df523558bd12121&redirect_uri=http%3a%2f%2fmarktest.clubexpress.com%2fbasic_modules%2fclub_admin%2fwebsite%2fauth_callback.aspx%3ftype%3dlinkedin
This also resulted in an error but was worth a shot.
The documetation here: https://developer.linkedin.com/forum/oauth-20-redirect-url-faq-invalid-redirecturi-error indicates that you CAN use query parameters. And in the first request, it appears that I'm doing it correctly. Post #25 on this page - https://developer.linkedin.com/forum/error-while-getting-access-token indicates that you have to remove the query parameters to make it work
Anyone have experience with successfully passing additional query paramaters in the callback url for the linkedin API using oAuth2.0? If so, what am I doing wrong?
I couldn't wait around for the Linkedin rep's to respond. After much experimentation, I can only surmise that the use of additional query parameters in the callback is not allowed (thanks for making my application more complicated). As it's been suggested in post #25 from the question, I've tucked away the things I need in the "state=" parameter of the request so that it's returned to my callback.
In my situation, I'm processing multiple API's from my callback and requests from multiple users, so I need to know the type and user number. As a solution, I'm attaching a random string to a prefix, so that I can extract the query parameter in my callback and process it. Each state= will therefore be unique as well as giving me a unique key to cache/get object from cache..
so state="Linkedin-5hnx5322d3-543"
so, on my callback page (for you c# folks)
_stateString=Request["state"];
_receivedUserId = _stateString.Split('-')[2];
_receivedCacheKeyPrefix = _stateString.Split('-')[0];
if(_receivedCacheKeyPrefix == "Linkedin") {
getUserDomain(_receivedUserId);
oLinkedIn.AccessTOkenGet(Request["code"],_userDomain);
if (oLinkedin.Token.Length > 0) {
_linkedinToken = oLinkedin.Token;
//now cache token using the entire _statestring and user id (removed for brevity)
}
You not allowed to do that.
Refer to the doc: https://developer.linkedin.com/docs/oauth2
Please note that:
We strongly recommend using HTTPS whenever possible
URLs must be absolute (e.g. "https://example.com/auth/callback", not "/auth/callback")
URL arguments are ignored (i.e. https://example.com/?id=1 is the same as https://example.com/)
URLs cannot include #'s (i.e. "https://example.com/auth/callback#linkedin" is invalid)