Unexpected token % in angularjs - javascript

Code:
$scope.username=JSON.parse(getCookie('authData')).Username;
This is what getCookie('authData') contains:
%7B%22UserID%22%3A%22c980b08240178f48a4607cd1d081664b%22%2C%22Username%22%3A%22sajeetharan%40duosoftware.com%22%2C%22Name%22%3A%22sajeetharan+sinnathurai%22%2C%22Email%22%3A%22sajeetharan%40duosoftware.com%22%2C%22SecurityToken%22%3A%22a7dd024d5158c7e1ee4807cb9716cc6f%22%2C%22Domain%22%3A%22sajeetharan.digin.io%22%2C%22DataCaps%22%3A%22%22%2C%22ClientIP%22%3A%22104.155.236.85%3A33776%22%2C%22Otherdata%22%3A%7B%22JWT%22%3A%22eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkbW4iOiJzYWplZXRoYXJhbi5kaWdpbi5pbyIsImVtbCI6InNhamVldGhhcmFuQGR1b3NvZnR3YXJlLmNvbSIsImlzcyI6InNhamVldGhhcmFuLmRpZ2luLmlvIiwic2NvcGUiOnt9LCJzdCI6ImE3ZGQwMjRkNTE1OGM3ZTFlZTQ4MDdjYjk3MTZjYzZmIiwidWlkIjoiYzk4MGIwODI0MDE3OGY0OGE0NjA3Y2QxZDA4MTY2NGIifQ%3D%3D.YpFKYAw0t3RQkbrM9sjY1QAkz4AUxsmlE5uXMy%5C%2Fsc%3D%22%2C%22Scope%22%3A%22%22%7D%7D
What could be the issue?

Try the function decodeURIComponent():
$scope.username=JSON.parse(
decodeURIComponent(getCookie('authData'))
).Username
The cookie value is just encoded.
Cookie values may not include semicolons, commas, or whitespace. For
this reason, you may want to use the JavaScript encodeURIComponent()
function to encode the value before storing it in the cookie. If you
do this, you will also have to use the corresponding
decodeURIComponent() function when you read the cookie value.
More details in this tutorial.

Related

Typescript JSON.parse turkish character conversion problem [duplicate]

This question already has answers here:
Using Javascript's atob to decode base64 doesn't properly decode utf-8 strings
(12 answers)
Closed last month.
I have a code that decodes JWT tokens, splits the string part that contains claims and converts that info into a JSON object.
return JSON.parse(atob(token.split('.')[1])) as LoggedInUser;
It works but when it comes to user's name, since it has some turkish characters, I get a string with non-readable characters. User's name is "Uğur Gül" in the picture below.
I think I should somehow parse with utf-8 formatting but can't find how to that. I'm working with angular framework. How can I fix this issue?
Edit: Here is a decoded version of my mock-data token on jwt.io. I'm trying to get the payload from token like the way jwt.io creates an JSON object, and I'm assigning needed values to related fields to an instance of LoggedInUser class.
One way is to escape and unescape the name on the backend/frontend. I don't know how your app works.
We use escape and Uğur Gül will converted to U%u011Fur%20G%FCl. Set this to GivenUserName, create the token and send it to the frontend. Frontend decodes it, gave the name and call unescape. So you have the correct name again.
Sample:
data = '{"UserId":"2","UserGivenName":"U%u011Fur%20G%FCl","http://schemas.microsoft.com/ws/2008/06/identity/claims/role":"2","exp":1672046375,"iss":"https://localhost:7013/","aud":"https://localhost:7013/"}'
constructor() {
console.log((escape("Uğur Gül")));
console.log(unescape(escape("Uğur Gül")))
this.token = (btoa(this.data))
const jsonData = JSON.parse(atob(this.token));
console.log(unescape(jsonData.UserGivenName));
}
Important
escape and unescape are marked as deprecated. You can use encodeURI and decodeURI instead:
console.log(encodeURI('Uğur Gül'));
console.log(decodeURI(encodeURI('Uğur Gül')));
Here is a Stackblitz to play.

Safari not saving cookie value correctly [duplicate]

In particular, when saving a JSON to the cookie is it safe to just save the raw value?
The reason I dopn't want to encode is because the json has small values and keys but a complex structure, so encoding, replacing all the ", : and {}, greatly increases the string length
if your values contain "JSON characters" (e.g. comma, quotes, [] etc) then you should probably use encodeURIComponent so these get escaped and don't break your code when reading the values back.
You can convert your JSON object to a string using the JSON.stringify() method then save it in a cookie.
Note that cookies have a 4000 character limit.
If your Json string is valid there should be no need to encode it.
e.g.
JSON.stringify({a:'foo"bar"',bar:69});
=> '{"a":"foo\"bar\"","bar":69}' valid json stings are escaped.
This is documented very well on MDN
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
If you can't be certain that your JSON will not include reserved characters such as ; then you will want to perform escaping on any strings being stored as a cookie. RFC 6265 covers special characters that are not allowed in the cookie-name or cookie-value.
If you are encoding static content you control, then this escaping may be unnecessary. If you are encoding dynamic content such as encoding user generated content, you probably need escaping.
MDN recommends using encodeURIComponent to escape any disallowed characters.
You can pull in a library such as cookie to handle this for you, but if your server is written in another language you will need to ensure it uses a library or language utilities to encodeURIComponent when setting cookies and to decodeURIComponent when reading cookies.
JSON.stringify is not sufficient as illustrated by this trivial example:
const bio = JSON.stringify({ "description": "foo; bar; baz" });
document.cookie = `bio=${stringified}`;
// Notice that the content after the first `;` is dropped.
// Attempting to JSON.parse this later will fail.
console.log(document.cookie) // bio={\"description\":\"foo;
Cookie: name=value; name2=value2
Spaces are part of the cookie separation in the HTTP Cookie header. Raw spaces in cookie values could thus confuse the server.

jQuery can't encode a parameter which is a URL

I have a GET request that takes a parameter, this parameter is also a URL. So normally I just encode the URL and then decode it in my server, this works pefectly from Java, but now I am on jQuery and I have a problem with it.
This is the value of that parameter:
http://www.BookOntology.com/bo#ania
When I encode it like this:
encodeURI(userURI)
I get the same value, while i thought that i should have gotten this
http%3A%2F%2Fwww.BookOntology.com%2Fbo%23ania
To show you what is the wrong
My current approach (which is using econdeURI) brings this final URL (note that I just want to encode the paramter not the whole URL).
http://bla bla bla?userURI=http://www.BookOntology.com/bo#ania
But in the server when i read the value of the userURI parameter i get:
http://www.BookOntology.com/bo
It is definitely a problem with the way i encode that value of that parameter because, again, the value after and before encoding is the same though the value contains some characters that should be changed.
Could you help me pass that please?
Try with encodeURIComponent function , which encodes a Uniform Resource Identifier (URI)
DEMO: encode input value
Read the MDN DOCS for more info.
encodeURI only changes characters that can't appear in a URL at all.
You're looking for encodeURIComponent which encodes all characters with special meaning in a URL as well (and makes it suitable for inserting in a query string).

Escape apostrophe in a string saved in a cookie

I need to save a string value in a cookie, and that string (a person's last name) may contain an apostrophe, like O'Bama.
I tried lastName.replace(/'/, "\'").toString(); but I get undefined in a cookie.
What am I doing wrong, and how should this be done correctly?
Use the escape() function in javascript:
lastname = escape(lastname);
To undo this operation just call unescape()...
This will encode all special chars to store them in your cookie.
Some reference: http://www.w3schools.com/jsref/jsref_escape.asp
you only need to escape the string using javascript function:
escape()
and unescape to get the actual value
unescape()

javascript escape problem with unicode characters

I use the following jquery code to load some date on a specific event from external file:
$("#container").load("/include/data.php?name=" + escape(name));
if the javascript "name" variable contains unicode characters it sends some encoded symbols to data.php file, something like this: %u10E1
How can I deal with this encoded symbols? I need to convert them back to readable one.
When I remove the escape function and leave just "name" variable the code doesn't work any more...
Can anyone please help?
If you want to do this manually, then you should be using encodeURIComponent, not escape (which is deprecated)
The jQuery way, however, would be:
$("#container").load("/include/data.php", { "name": name });
Either way PHP should decode it automatically when it populates $_GET.
This may help you.
javascript - how to convert unicode string to ascii

Categories

Resources