user7474631
user7474631

Reputation:

Cannot access session data in Ember (JWT Token Data)

I'm using JWT authentication, using ember-simple-auth for implementing user authentication. I m providing necessary details in my project below.

When Authenticated correctly a jwt token is passing from the backend made of djangorest and it contains only a token.

/app/authenticators/jwt.js

import Ember from 'ember';
import Base from 'ember-simple-auth/authenticators/base';
import config from '../config/environment';

const { RSVP: { Promise }, $: { ajax }, run } = Ember;
export default Base.extend({

  tokenEndpoint: `http://localhost:8000/auth`,

  restore(data) {
    return new Promise((resolve, reject) => {
      // console.log(data.token); token seems empty
      if (!Ember.isEmpty(data.token)) {
        resolve(data);
      } else {
        reject();
      }
    });
  },

  authenticate(creds) {
    const { identification, password } = creds;
    const data = JSON.stringify({
        email: identification,
        password: password
    });
    const requestOptions = {
      url: this.tokenEndpoint,
      type: 'POST',
      data,
      contentType: 'application/json',
      dataType: 'json'
    };
    return new Promise((resolve, reject) => {
      ajax(requestOptions).then((response) => {
        // console.log(response); verified
        const { jwt } = response;
        // Wrapping aync operation in Ember.run
        run(() => {
          resolve({
            token: jwt
          });
        });
      }, (error) => {
        // Wrapping aync operation in Ember.run
        run(() => {
          reject(error);
        });
      });
    });
  },

   invalidate(data) {
     return Promise.resolve(data);
   }
});

/app/authorizer/custom.js

import Base from 'ember-simple-auth/authorizers/base';
// import Ember from 'ember';
import { inject } from '@ember/service';

export default Base.extend({
  session: inject('session'),
  authorize(data, block) {
    const { token } = data
    if (this.get('session.isAuthenticated') && token) {
      consol.log(token);
      // this._super(...arguments);
      block('Authorization', `JWT ${token}`);
      console.log(Authorization);
    }
  }
});

As I tried to access the token using session.data.authenticated.token it shows the value undefined.

Upvotes: 0

Views: 232

Answers (1)

robertoplancarte
robertoplancarte

Reputation: 1181

If your response from /auth looks like this:

{access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDA0MTU0ODgsInN1YiI6MSwicm9sZSI6MCwibmFtZSI6IlJvYmVydG8iLCJlbWFpbCI6InJwbGFuY2FyQHRlc3QuY29tIn0.okZCipPGuPSmgC5B0h7QkldBkVPDvdut7I7u-fFE61w"}

and you can use the JWT page to decode it and it works then check to see if session.session.content.authenticated is defined. It should hold the token string. If it is you should be able to decode it and use the information... something like:

tokenData: Ember.computed('session.session.content.authenticated', function(){
  var token = this.get('session.session.content.authenticated');
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace('-','+').replace('_', '/'); //so the atob function works 
  return JSON.parse(window.atob(base64));
})

You can just add that to your application controller or make it a service to use it all over your site.

Upvotes: 1

Related Questions