Skip to content

Commit 664949f

Browse files
fmquagliarichmolj
authored andcommitted
Set custom Authorization Token through generateAuthHeader class method (#34)
* #27 Added method generateAuthHeader to override default token format with a custom one.
1 parent 047fd94 commit 664949f

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/model.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ export default class Model {
8686
}
8787

8888
if (this.getJWT()) {
89-
options.headers.Authorization = `Token token="${this.getJWT()}"`;
89+
options.headers.Authorization = this.generateAuthHeader(this.getJWT());
9090
}
9191

9292
return options
@@ -183,6 +183,10 @@ export default class Model {
183183
return deserialize(resource, payload);
184184
}
185185

186+
static generateAuthHeader(jwt: string) : string {
187+
return `Token token="${jwt}"`;
188+
}
189+
186190
constructor(attributes?: Object) {
187191
this._initializeAttributes();
188192
this.attributes = attributes;

test/integration/authorization-test.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { sinon, expect, fetchMock } from '../test-helper';
22
import { Config } from '../../src/index';
3-
import { configSetup, ApplicationRecord, Author } from '../fixtures';
3+
import { configSetup, ApplicationRecord, Author, Person } from '../fixtures';
44

55
after(function () {
66
fetchMock.restore();
@@ -27,6 +27,30 @@ describe('authorization headers', function() {
2727
});
2828
});
2929

30+
describe('when header is set in a custom generateAuthHeader', function() {
31+
let originalHeaderFn = Person.generateAuthHeader;
32+
beforeEach(function() {
33+
ApplicationRecord.jwt = 'cu570m70k3n';
34+
Person.generateAuthHeader = function(token) {
35+
return `Bearer ${token}`;
36+
};
37+
});
38+
39+
afterEach(function() {
40+
fetchMock.restore();
41+
Person.generateAuthHeader = originalHeaderFn;
42+
});
43+
44+
it("sends the custom Authorization token in the request's headers", function(done) {
45+
fetchMock.mock((url, opts) => {
46+
expect(opts.headers.Authorization).to.eq('Bearer cu570m70k3n');
47+
done();
48+
return true;
49+
}, 200);
50+
Person.find(1);
51+
});
52+
});
53+
3054
describe('when header is NOT returned in response', function() {
3155
beforeEach(function() {
3256
fetchMock.get('http://example.com/api/v1/authors', {

0 commit comments

Comments
 (0)