Authenticating url on server side

In client side I have written my code as below,

$.ajax({
 type: "GET",
 beforeSend: function (request) {
  var jwt = document.head.querySelector("[name~=token][content]").content;
  request.setRequestHeader("Authorization", 'JWT '+ jwt);
 },
 url: "/test",
 success: function(data){
   alert("success");
 }
});

using this ajax request from client side I want to get the data on server side by authenticating the jwt token sent from client side. Server side(router code) is below,

app.get('/test', addon.checkValidToken(), function(req, res){
 ....
});

So, how can I authenticate or validate the url using jwt token by sending through request.SetHeaderRequest? I referred this url, but I couldn’t figure out any solution for it.

Also, I referred another link. It was mentioned that Get method was working with that code, but unfortunately it didn’t work for me. So, can anyone give me a solution for this?

2 Likes

Hi @hariprasath.

I saw your posts here and here.

In your server side code (router), to have your calls authenticated with jwt, if you’re using ACE, what I do is have the addon.authenticate() as part of the dependency as such:

If you’re using your add-on user to invoke REST APIs:

app.get('/hello-world', addon.authenticate(), function (req, res) {
    let httpClient = addon.httpClient(req);

    httpClient.get({
                url: `rest/api/<version>/<endpoint>`,
                contentType: 'application/json',
                json: true
            }, (error, res, body) => {
                //do something about the body
            });
});

If you’re acting as a user:

httpClient.asUser('admin').get({
                url: `rest/api/<version>/<endpoint>`,
                contentType: 'application/json',
                json: true
            }, (error, res, body) => {
                //do something about the body
            });

Cheers,
Anne Calantog

1 Like

Hi @acalantog,

I have used the code in client side as below,

$.ajax({
	type: "GET",
	url: "/hello-world",
	dataType: "json",
	contentType: "application/json",
	success: function(data){
		// my code
	}
});

and in server side as,

app.get('/hello-world', addon.authenticate(), function (req, res) {
        ...    
});

Still I get the issue - ‘Authentication verification error: 401 Could not find authentication data on req
uest’, when the above code is used in server side(add-on user to invoke REST APIs).

1 Like

Hi @hariprasath,

Hmm, I see. I think I understand now what you want to do. So I have this in my server side:

app.get('/get-via-jwt', addon.checkValidToken(), function() {
    console.log('Able to access this!');
});

And for me to access this resource in my js from the front-end, I added a meta tag:
<meta name="token" content="{{token}}"/>

and in my js, this is how I call the endpoint:

let jwt_token = $('meta[name="token"]').attr('content');

$.ajax({
    url: "/get-via-jwt",
    type: "GET",
    headers: {
        'Authorization' : `JWT ${jwt_token}`
    },
    success: function() { alert('Success!' + authHeader); }
});

And you should be able to access your endpoint that’s validated by jwt.

Let me know if you need anything else.

Cheers,
Anne Calantog

5 Likes

Hi @acalantog,

Thanks a lot. It works perfectly. Now, I am able to validate the ajax request using the jwt token.

Cheers,
Hari Prasath

Hello @acalantog

I have another question over here. When I load the page, I can get jwt token within meta tag. But, when redirecting to another page, there I do not find jwt token, the content within tag is empty when inspected.

<meta name="token" content=""/>

So, how can I access jwt token there?

Hi.
I’m attempting to do exactly what is shown in your example.
However I am getting the following error.

{} Authentication verification error (401): Invalid JWT: Not enough or too many JWT token segments; should be 3.

Are there any updates on how this should be done?

1 Like

Worked for me as well.

  • Add the token in html head tag: <meta name="token" content="{{token}}">
  • Extract the token in script: var token = document.querySelector('meta[name="token"]').content
  • Append Authorization in request headers before sending request back to addon (server) from iframe client (Jira in my case) RequestHeaders["Authorization"] = "JWT ${token}"
  • Lastly, use addon.checkValidToken() in your route instead of addon.authenticate()