Simple JWT Auth using Jquery - javascript

I am trying to do a simple JWT Authentication using only JQuery. I have already tested the backend with postman and everything seems to work in there.
Here's how my frontend code looks like
$("#send").click(function(){
var name = $('#name').val();
var password = $('#password').val();
var token = ''
$.ajax({
type: 'POST',
url: '/authenticate',
data: { name: name , password: password },
success: function(resultData){
var token = resultData.token;
// console.log(token);
$.ajax({
type: 'GET',
url: '/memberinfo',
headers: {"Authorization": token},
success: function(data){
$(location).attr('href', '/memberinfo')
}
});
}
});
});
so when I get redirected to the memberinfo page it shows me I am unauthorised. Not quite sure if I am doing the Ajax calls properly. Would be really helpful if some one could direct me the right way. Thanks

For simple use case just retrieve a token in the login request response and save it to the localStorage or sessionStorage. Then use the token from the localStorage inside every request header.
Please, have a look at an example code here.
https://github.com/chaofz/jquery-jwt-auth
On the other hand that is not secure to store a token in these storages as it is not protected from XSS attacks.
You better store token in cookies and check your cookies policies to prevent CSRF attack.
Please read more here

i may be wrong, but a quick look of your code it might be because you set the api call for GET request and your client page the same url /memberinfo. your test result using Postman is working and also you are properly redirected to the /memberinfo upon success validation, however, since you are redirected to the same /memberinfo url and your browser didn't send headers: {"Authorization": token} you received unauthorised result.
try to make the api call url different with the client member page.

You need to add word "Bearer":
headers: {"Authorization": "Bearer " + token}, // note the space after Bearer

Related

in Ajax, how to write "headers" for multiple condition?

as a beginner, I have some problems in using Ajax (with Discogs API) .. to get a discogs request token, discogs is saying
Include the following headers with your request:
Content-Type: application/x-www-form-urlencoded
Authorization:
OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback"
User-Agent: some_user_agent
https://www.discogs.com/developers#page:authentication,header:authentication-discogs-auth-flow
but, how to write this header?
below is my trying code, but I know this is not proper.
$.ajax({
type: "GET",
url: "https://api.discogs.com/oauth/request_token",
dataType: 'jsonp',
headers: {
ContentType: "application/x-www-form-urlencoded",
Authorization: OAuth oauth_consumer_key="your_consumer_key",
oauth_nonce="random_string_or_timestamp",
oauth_signature="your_consumer_secret&",
oauth_signature_method="PLAINTEXT",
oauth_timestamp="current_timestamp",
oauth_callback="your_callback",
UserAgent: some_user_agent,
}
success: function (data) {
console.log(data);
document.getElementById("content").innerHTML += "<br>" + `${data}`;
},
error: function (error) {
console.log(error);
}
});
You said:
dataType: 'jsonp',
It isn't possible to specify headers for JSONP requests.
The API can't be using JSONP. Set the dataType to the format they are using.
The documentation says:
When you create a new application, you’ll be granted a Consumer Key and Consumer Secret, which you can plug into your application and start making authenticated requests. It’s important that you don’t disclose the Consumer Secret to anyone.
Putting those in your client-side code will disclose them to all your visitors.
The request to that end point should be made from server-side code.

Google translation Oauth2.0 from browser

I am creating a simple web page, that make use of the Google Translation Service.
The page has a field, to receive the input from the user and a button to trigger the call to the Translation API. It returns the result translation to the user.
I've successfully done the flow above using Ajax requests, but the access token
is hard-coded into my method and I want to change that to a call that gets sent whenever the token expires (currently I have to request a new token using the Google CLI and replace it in my code).
I have a very basic knowledge of Oauth2.0 and I've read the Google Documentation but couldn't find a part of it that would tell me the endpoint to call to get an access token from the client-side.
Could someone point me in the right direction, please?
Here is my code:
HTML:
<form id="translate_form">
<input id="input" />
<button id="translate_button">Translate</button>
</form>
Javascript
$("#translate_form").submit(function () {
var text = $("#input").val()
sendTranslationRequest(text);
return false;
})
function sendTranslationRequest(inputText) {
var requestBody = {
q: inputText,
source: "en",
target: "fr",
format: 'text'
}
translationAjaxRequest(requestBody);
}
function translationAjaxRequest(requestBody) {
var access_token = [access_token]
$.ajax({
url: "https://translation.googleapis.com/language/translate/v2",
method: "POST",
contentType: "application/json",
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Bearer " + access_token)
},
data: JSON.stringify(requestBody),
success: function (response) {
var translatedText = response.data.translations[0].translatedText
alert(translatedText)
},
error: function () {
console.log("An error occurred on the request:", response)
}
});
}
The relevant endpoints to get an access token and refresh it are:
https://accounts.google.com/o/oauth2/v2/auth
https://www.googleapis.com/oauth2/v4/token
However, you’ll need to perform several steps in order to get an access token and a refresh token. You may want to review this guide on Using OAuth2.0 for Web Server Applications. It will walk you through the prerequisites, obtaining an access token and refreshing your token.
Alternatively, you may use an API Key. Just be mindful of the recommendations on how to secure it, since a stolen API Key may be used to generate calls that would be charged directly to your billing account.

HTTP GET request to server only occasionally works

I am using jQuery Ajax to make a GET request. Sometimes It works perfectly, but other times I get a 403 forbidden when I look at the chrome dev tools console. Is this a server issue or my code?
When I sign in, I get the encrypted password, username and ID back from the server. I then store that in LocalStorage since the request I am trying to get working is on another page. I am also required to make a client token from those fields using AES encryption. For that, I am using CryptoJS. For my request, I am required to send in the password, username, ID and client token that has been retrieved from LocalStorage. I realize that may not be a good way to go about it, but I do not have control of the server side.
Edit: Here is my Ajax call to the service:
$("#system-form").submit(function (e) {
$.ajax({
type: "GET",
url: "myurl",
data: "User.Username=" + localStorage.getItem("guid") + "&User.Password=" + localStorage.getItem("password") + "&User.SecUser=" + localStorage.getItem("secUser") + "&ClientAppID=" + localStorage.getItem("ClientAppId") +"&"+ $(this).serialize(),
})
.done(function(data) {
//parse data
})
.fail(function (xhr, textStatus, error) {
console.log(JSON.stringify(xhr.responseText));
});
e.preventDefault();
});
I realized my issue was that I need to URL encode my auth parameters. I fixed this by using encodeURIComponent.

How to access hp alm with rest api javascript: automatic login

I just want to access ALM via local written javascript in the browser (IE11, Firefox, Chrome) via the REST API but I can not login.
I tried to use the code shown in How to access HP ALM using REST and local javascript? , but there is always the same Error: OPTIONS https://alm.....net/qcbin/authentication-point/authenticate 401 (An Authentication object was not found in the SecurityContext)
Maybe the problem is, that I don't know how to
submit my credentials via XML
as mentioned in the link. Could you please help me?
Me Code is:
function signinTest() {var auth = btoa(name + ":" + password);
$.ajax({
type: "POST",
url: 'https://alm.....net/qcbin/authentication-point/authenticate',
headers: {
"Authorization": "Basic " + auth
},
xhrFields: {
withCredentials: true
},
success: function (data) {
console.log("succes " + data);
},
error: function (data) {
console.log("error ");
console.log(data);
}
});
}
Seems like you have mixed
/authentication-point/alm-authenticate
and
/authentication-point/authenticate
REST resources.
If you want to log in using credentials in XML you need to use alm-authenticate resource (see alm-authenticate doc).
For authenticate you need to send user information in headers and use GET method (see Authenticate doc).
Use data and contentType to send XML via Ajax in the POST.
For example:
function signinTest() {var auth = btoa(name + ":" + password);
$.ajax({
url: 'https://alm.....net/qcbin/authentication-point/alm-authenticate',
data: "<alm-authentication><user>USERNAME</user><password>PASSWORD</password></alm-authentication>",
type: "POST",
contentType: "text/xml",
...

Get and store cookie (from Set-Cookie) from an AJAX POST response

I have a simple jQuery AJAX POST code:
$.ajax({
type: "POST",
url: AppConstants.URLs.PROXY,
data: message,
xhrFields: {
withCredentials: true
},
success: function(data, status, xhr) {
console.log("Cookie: " + xhr.getResponseHeader("Set-Cookie"));
}
});
and I wish to get the cookie and save it using cookies-js.
But according to http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders%28%29-method:
Return all response headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.
Using the Network tool in Chrome, "Set-Cookie" is visible in the Response headers. I also verified that the "Set-Cookie" header appears using curl.
What do I have to do to save the cookie in my front end app? Also, my app is running on https only.
I'd gladly provide more details upon request.
You can't get the cookie data in your JS. The API won't allow you.
What do I have to do to save the cookie in my front end app?
Just set the Set-Cookie header in the response from the server side code. The browser should save it automatically.
As a developer, you may be able to inspect the value of the cookies using "Developer Tools".
And the same cookie will be sent in subsequent requests to the same domain, until the cookie expires.
The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!
For this to work you need to:
1) login with the ajax request from which you expect cookies to be returned:
$.ajax("https://example.com/v2/login", {
method: 'POST',
data: {login_id: user, password: password},
crossDomain: true,
success: login_success,
error: login_error
});
2) Connect with xhrFields: { withCredentials: true } in the next ajax request(s) to use the credentials saved by the browser
$.ajax("https://example.com/v2/whatever", {
method: 'GET',
xhrFields: { withCredentials: true },
crossDomain: true,
success: whatever_success,
error: whatever_error
});
The browser takes care of these cookies for you even though they are not readable from the headers nor the document.cookie
see my answer here: How to get a cookie from an AJAX response?

Categories

Resources