Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add client-side authentication features #8806

Merged
merged 18 commits into from
Aug 7, 2020
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -369,3 +369,97 @@ export class ConnectClient {
}
}
}

export interface LoginResult {
token?: string;
error: boolean;
errorTitle: string;
errorMessage: string;
}

export async function login(username: string, password: string): Promise<LoginResult> {
let result;
try {
// this assumes the default Spring Security form login configuration (parameter names)
const data = new FormData();
data.append('username', username);
data.append('password', password);

const response = await fetch('/login', {method: 'POST', body: data});
Haprog marked this conversation as resolved.
Show resolved Hide resolved

// this assumes the default Spring Security form login configuration (handler URL and responses)
if (response.ok && response.redirected && response.url.endsWith('/login?error')) {
result = {
error: true,
errorTitle: 'Incorrect username or password.',
errorMessage: 'Check that you have entered the correct username and password and try again.'
};
} else if (response.ok && response.redirected && response.url.endsWith('/')) {
// TODO: find a more efficient way to get a new CSRF token
// parsing the full response body just to get a token may be wasteful
const token = getCsrfTokenFromResponseBody(await response.text());
if (token) {
(window as any).Vaadin.TypeScript = (window as any).Vaadin.TypeScript || {};
(window as any).Vaadin.TypeScript.csrfToken = token;
result = {
error: false,
errorTitle: '',
errorMessage: '',
token
};
}
}
} catch (e) {
result = {
error: true,
errorTitle: e.name,
errorMessage: e.message
}
}

return result || {
error: true,
errorTitle: 'Communication error.',
errorMessage: 'Please check your network connection and try again.',
};
}

export async function logout() {
// this assumes the default Spring Security logout configuration (handler URL)
const response = await fetch('/logout');

// TODO: find a more efficient way to get a new CSRF token
// parsing the full response body just to get a token may be wasteful
const token = getCsrfTokenFromResponseBody(await response.text());
(window as any).Vaadin.TypeScript.csrfToken = token;
}

const getCsrfTokenFromResponseBody = (body: string): string | undefined => {
const match = body.match(/window\.Vaadin = \{TypeScript: \{"csrfToken":"([0-9a-zA-Z\-]{36})"}};/i);
return match ? match[1] : undefined;
}

export type EndpointCallContinue = (token: string) => void;
export type OnInvalidSessionCallback = (continueFunc: EndpointCallContinue) => void;

export class InvalidSessionMiddleWare {
static create(onInvalidSessionCallback: OnInvalidSessionCallback){
const middleWare = async (context: MiddlewareContext, next: MiddlewareNext): Promise<Response> => {
const clonedContext = { ...context };
clonedContext.request = context.request.clone();
const response = await next(context);
if (response.status === 401) {
return new Promise(async resolve => {
const continueFunc = (token: string) => {
clonedContext.request.headers.set('X-CSRF-Token', token);
resolve(next(clonedContext));
}
onInvalidSessionCallback(continueFunc);
});
} else {
return response;
}
};
return middleWare;
}
}
121 changes: 113 additions & 8 deletions flow-client/src/test/frontend/ConnectTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const {expect} = intern.getPlugin('chai');
const {fetchMock} = intern.getPlugin('fetchMock');
const {sinon} = intern.getPlugin('sinon');

import { ConnectClient, EndpointError, EndpointValidationError, EndpointResponseError } from "../../main/resources/META-INF/resources/frontend/Connect";
import { ConnectClient, EndpointCallContinue, EndpointError, EndpointResponseError, EndpointValidationError, InvalidSessionMiddleWare, login, logout } from "../../main/resources/META-INF/resources/frontend/Connect";

// `connectClient.call` adds the host and context to the endpoint request.
// we need to add this origin when configuring fetch-mock
Expand Down Expand Up @@ -283,7 +283,7 @@ describe('ConnectClient', () => {
describe('middleware invocation', () => {
it('should not invoke middleware before call', async() => {
const spyMiddleware = sinon.spy(async(context: any, next?: any) => {
return await next(context);
return next(context);
});
client.middlewares = [spyMiddleware];

Expand All @@ -296,7 +296,7 @@ describe('ConnectClient', () => {
expect(context.method).to.equal('fooMethod');
expect(context.params).to.deep.equal({fooParam: 'foo'});
expect(context.request).to.be.instanceOf(Request);
return await next(context);
return next(context);
});
client.middlewares = [spyMiddleware];

Expand All @@ -318,13 +318,12 @@ describe('ConnectClient', () => {
myUrl,
{
method: 'POST',
headers: Object.assign({}, context.request.headers, {
'X-Foo': 'Bar'
}),
headers: {...context.request.headers,
'X-Foo': 'Bar'},
body: '{"baz": "qux"}'
}
);
return await next(context);
return next(context);
};

client.middlewares = [myMiddleware];
Expand Down Expand Up @@ -357,7 +356,7 @@ describe('ConnectClient', () => {

const secondMiddleware = sinon.spy(async(context: any, next?: any) => {
(expect(firstMiddleware).to.be as any).calledOnce;
return await next(context);
return next(context);
});

client.middlewares = [firstMiddleware, secondMiddleware];
Expand Down Expand Up @@ -396,5 +395,111 @@ describe('ConnectClient', () => {
await client.call('FooEndpoint', 'fooMethod', {fooParam: 'foo'});
});
});

describe('login', () => {
afterEach(() => fetchMock.restore());

it('on invalid credential', async () => {
Haprog marked this conversation as resolved.
Show resolved Hide resolved
fetchMock.post('/login', { redirectUrl: '/login?error' });
const result = await login('invalid-username', 'invalid-password');
const expectedResult = {
error: true,
errorTitle: 'Incorrect username or password.',
errorMessage: 'Check that you have entered the correct username and password and try again.'
};

expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})

it('on valid credential', async () => {
Haprog marked this conversation as resolved.
Show resolved Hide resolved
fetchMock.post('/login', {
body: 'window.Vaadin = {TypeScript: {"csrfToken":"6a60700e-852b-420f-a126-a1c61b73d1ba"}};',
redirectUrl: '/'
});
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: false,
errorTitle: '',
errorMessage: '',
token: '6a60700e-852b-420f-a126-a1c61b73d1ba'
};

expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})

it('on other erros', async () => {
Haprog marked this conversation as resolved.
Show resolved Hide resolved
const body = 'Unexpected error';
const errorResponse = new Response(
body,
{
status: 500,
statusText: 'Internal Server Error'
}
);
fetchMock.post('/login', errorResponse);
const result = await login('valid-username', 'valid-password');
const expectedResult = {
error: true,
errorTitle: 'Communication error.',
errorMessage: 'Please check your network connection and try again.'
};

expect(fetchMock.calls()).to.have.lengthOf(1);
expect(result).to.deep.equal(expectedResult);
})
})
});

describe("logout", () => {
it('should set the csrf token on logout', async () => {
fetchMock.get('/logout', {
body: 'window.Vaadin = {TypeScript: {"csrfToken":"6a60700e-852b-420f-a126-a1c61b73d1ba"}};',
redirectUrl: '/logout?login'
});
await logout();
expect(fetchMock.calls()).to.have.lengthOf(1);
expect((window as any).Vaadin.TypeScript.csrfToken).to.equal("6a60700e-852b-420f-a126-a1c61b73d1ba");
});
});

describe("InvalidSessionMiddleWare", ()=>{
afterEach(() => fetchMock.restore());

it("should invoke the onInvalidSession callback on 401 response", async ()=>{
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', 401)

const invalidSessionCallback = sinon.spy((continueFunc: EndpointCallContinue)=>{
// mock to pass authentication
fetchMock.restore();
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', {fooData: 'foo'})
continueFunc("csrf-token");
});
const middleware = InvalidSessionMiddleWare.create(invalidSessionCallback);

const client = new ConnectClient({middlewares:[middleware]});

await client.call('FooEndpoint','fooMethod');

expect(invalidSessionCallback.calledOnce).to.be.true;

const headers = fetchMock.lastOptions().headers;
expect(headers).to.deep.include({
'x-csrf-token': 'csrf-token'
});
})

it("should not invoke the onInvalidSession callback on 200 response", async ()=>{
fetchMock.post(base + '/connect/FooEndpoint/fooMethod', {fooData: 'foo'})

const invalidSessionCallback = sinon.spy();
const middleware = InvalidSessionMiddleWare.create(invalidSessionCallback);

const client = new ConnectClient({middlewares:[middleware]});
await client.call('FooEndpoint', 'fooMethod');

expect(invalidSessionCallback.called).to.be.false;
})
});
});