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 all 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
159 changes: 154 additions & 5 deletions flow-client/src/main/resources/META-INF/resources/frontend/Connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,15 +207,31 @@ export interface MiddlewareContext {
export type MiddlewareNext = (context: MiddlewareContext) =>
Promise<Response> | Response;


/**
* An interface that allows defining a middleware as a class.
*/
export interface MiddlewareClass {
/**
* @param context The information about the call and request
* @param next Invokes the next in the call chain
*/
invoke(context: MiddlewareContext, next: MiddlewareNext): Promise<Response> | Response;
}

/**
* An async callback function that can intercept the request and response
* of a call.
* @param context The information about the call and request
* @param next Invokes the next in the call chain
*/
export type Middleware = (context: MiddlewareContext, next: MiddlewareNext) =>
type MiddlewareFunction = (context: MiddlewareContext, next: MiddlewareNext) =>
Promise<Response> | Response;

/**
* An async callback that can intercept the request and response
* of a call, could be either a function or a class.
*/
export type Middleware = MiddlewareClass | MiddlewareFunction;

/**
* Vaadin Connect client class is a low-level network calling utility. It stores
* a prefix and facilitates remote calls to endpoint class methods
Expand Down Expand Up @@ -344,15 +360,21 @@ export class ConnectClient {

// Assemble the final middlewares array from internal
// and external middlewares
const middlewares = [responseHandlerMiddleware].concat(this.middlewares);
const middlewares = [responseHandlerMiddleware as Middleware].concat(this.middlewares);

// Fold the final middlewares array into a single function
const chain = middlewares.reduceRight(
(next: MiddlewareNext, middleware: Middleware) => {
// Compose and return the new chain step, that takes the context and
// invokes the current middleware with the context and the further chain
// as the next argument
return (context => middleware(context, next)) as MiddlewareNext;
return (context => {
if(typeof middleware === 'function'){
return middleware(context, next);
}else {
return (middleware as MiddlewareClass).invoke(context, next);
}
}) as MiddlewareNext;
},
// Initialize reduceRight the accumulator with `fetchNext`
fetchNext
Expand All @@ -369,3 +391,130 @@ export class ConnectClient {
}
}
}

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

export interface LoginOptions{
loginProcessingUrl?: string;
failureUrl?: string;
defaultSuccessUrl?: string;
}

export interface LogoutOptions{
logoutUrl?: string;
}

/**
* A helper method for Spring Security based form login.
* @param username
* @param password
* @param options defines additional options, e.g, the loginProcessingUrl, failureUrl, defaultSuccessUrl etc.
*/
export async function login(username: string, password: string, options?: LoginOptions): Promise<LoginResult> {
let result;
try {
const data = new FormData();
data.append('username', username);
data.append('password', password);

const loginProcessingUrl = options && options.loginProcessingUrl ? options.loginProcessingUrl : '/login';
const response = await fetch(loginProcessingUrl, {method: 'POST', body: data});

const failureUrl = options && options.failureUrl ? options.failureUrl : '/login?error';
const defaultSuccessUrl = options && options.defaultSuccessUrl ? options.defaultSuccessUrl : '/'
// this assumes the default Spring Security form login configuration (handler URL and responses)
if (response.ok && response.redirected && response.url.endsWith(failureUrl)) {
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(defaultSuccessUrl)) {
// 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: 'Error',
errorMessage: 'Something went wrong when trying to login.',
};
}

/**
* A helper method for Spring Security based form logout
* @param options defines additional options, e.g, the logoutUrl.
*/
export async function logout(options?: LogoutOptions) {
// this assumes the default Spring Security logout configuration (handler URL)
const logoutUrl = options && options.logoutUrl ? options.logoutUrl : '/logout';
const response = await fetch(logoutUrl);

// 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;
}

type EndpointCallContinue = (token: string) => void;

/**
* It defines what to do when it detects a session is invalid. E.g.,
* show a login view.
* It takes an <code>EndpointCallContinue</code> parameter, which can be
* used to continue the endpoint call.
*/
export type OnInvalidSessionCallback = (continueFunc: EndpointCallContinue) => void;

/**
* A helper class for handling invalid sessions during an endpoint call.
* E.g., you can use this to show user a login page when the session has expired.
*/
export class InvalidSessionMiddleware implements MiddlewareClass {
constructor(private onInvalidSessionCallback: OnInvalidSessionCallback) {}

async invoke(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));
}
this.onInvalidSessionCallback(continueFunc);
});
} else {
return response;
}
}
}
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('should return an error on invalid credentials', async () => {
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('should return a CSRF token on valid credentials', async () => {
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('should return an error on other unexpected responses', async () => {
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: 'Error',
errorMessage: 'Something went wrong when trying to login.'
};

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 = new InvalidSessionMiddleware(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 = new InvalidSessionMiddleware(invalidSessionCallback);

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

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