Skip to content

Commit

Permalink
Step 7.25: Add authentication middleware for requests
Browse files Browse the repository at this point in the history
  • Loading branch information
srtucker22 authored and Simon Tucker committed Aug 26, 2018
1 parent 7c47b0c commit 8c0963e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"apollo-cache-redux": "^0.1.0-alpha.7",
"apollo-client": "^2.2.5",
"apollo-link": "^1.1.0",
"apollo-link-context": "^1.0.5",
"apollo-link-error": "^1.0.7",
"apollo-link-http": "^1.3.3",
"apollo-link-redux": "^0.2.1",
Expand Down
20 changes: 19 additions & 1 deletion client/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,15 @@ import { SubscriptionClient } from 'subscriptions-transport-ws';
import { PersistGate } from 'redux-persist/lib/integration/react';
import { persistStore, persistCombineReducers } from 'redux-persist';
import thunk from 'redux-thunk';
import { setContext } from 'apollo-link-context';
import _ from 'lodash';

import AppWithNavigationState, {
navigationReducer,
navigationMiddleware,
} from './navigation';
import auth from './reducers/auth.reducer';
import { logout } from './actions/auth.actions';

const URL = 'localhost:8080'; // set your comp's url here

Expand Down Expand Up @@ -61,6 +64,21 @@ const errorLink = onError((errors) => {

const httpLink = createHttpLink({ uri: `http://${URL}` });

// middleware for requests
const middlewareLink = setContext((req, previousContext) => {
// get the authentication token from local storage if it exists
const { jwt } = store.getState().auth;
if (jwt) {
return {
headers: {
authorization: `Bearer ${jwt}`,
},
};
}

return previousContext;
});

// Create WebSocket client
export const wsClient = new SubscriptionClient(`ws://${URL}/graphql`, {
reconnect: true,
Expand All @@ -85,7 +103,7 @@ const link = ApolloLink.from([
reduxLink,
errorLink,
requestLink({
queryOrMutationLink: httpLink,
queryOrMutationLink: middlewareLink.concat(httpLink),
subscriptionLink: webSocketLink,
}),
]);
Expand Down

0 comments on commit 8c0963e

Please sign in to comment.