Zorig
Zorig

Reputation: 605

Django rest + ember simple auth The authenticator “authenticator:oauth2” rejected to restore the session - invalidating

I use django rest framework and token auth as a backend auth. From backend token comes as this format when user credentials submitted

{token: "cKCxxxxxxxxxxxxxxxxxxxxx"}

on the frontend ember-simple auth i use oauth2 as a authenticator when i try to login it says:

The authenticator "authenticator:oauth2" rejected to restore the session - invalidating…

and session is not saved it logged in but when the route change it logged out. How do i append token in headers? It has to be appended automatically when use ember-simple-auth right or i get that wrong???

login.js

actions: {
  authenticate(username, password) {
    var controller = this.controller;         
    this.get('session').authenticate('authenticator:oauth2', username, password).catch((reason) => {
      controller.set('errorMessage', reason.detail || reason);
      console.log(this.get('session.data.authenticated'));
    });
  } 
}

and authenticator:

import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';

export default OAuth2PasswordGrant.extend({
  serverTokenEndpoint: 'http://127.0.0.1:8000/api/auth/login/',
});

authorizer: import OAuth2Bearer from 'ember-simple-auth/authorizers/oauth2-bearer';

export default OAuth2Bearer.extend({
});

adapter:

import DS from 'ember-data';
import DataAdapterMixin from 'ember-simple-auth/mixins/data-adapter-mixin';

export default DS.RESTAdapter.extend(DataAdapterMixin, {
  host: 'http://127.0.0.1:8000',
  namespace: 'api',
  authorizer: 'authorizer:oauth2',
});

Upvotes: 0

Views: 370

Answers (1)

Rohan Thacker
Rohan Thacker

Reputation: 11

TLDR : Ember Social API Looks for access_token while DRF send out token

Server-Side Fix

You need to subclass TokenSerializer and override keyword = Bearer

Client Side Fix

The OAuth2Bearer expects a token value called access_token, and if this value exists it will add the Authorization header with a Bearer prefix. However DRF Token expects the Authorization header to be prefixed with Token, see code below to better under stand

Working Authorizer for DRF TOKEN

import Ember from 'ember';
import Base from 'ember-simple-auth/authorizers/base';

const { isEmpty } = Ember;

export default Base.extend({
authorize(data, block) {
    const accessToken = data['token'];

    if (!isEmpty(accessToken)) {
      block('Authorization', `Token ${accessToken}`);
    }
  }
});

Reference to orignal OAuth2Bearer

Ember Social Auth - OAuth2Bearer

Upvotes: 1

Related Questions