React + Redux - JWT Authentication Tutorial & Example
For documentation and further details go to https://jasonwatmore.com/post/2017/12/07/react-redux-jwt-authentication-tutorial-example
React + Redux - JWT Authentication Tutorial & Example
Home Page: https://jasonwatmore.com/post/2017/12/07/react-redux-jwt-authentication-tutorial-example
License: MIT License
React + Redux - JWT Authentication Tutorial & Example
For documentation and further details go to https://jasonwatmore.com/post/2017/12/07/react-redux-jwt-authentication-tutorial-example
Hello.
Trying to make it working. Even ubunu reinstalling didn't help.
Did everything as explained here:
https://jasonwatmore.com/post/2017/12/07/react-redux-jwt-authentication-tutorial-example
Installed node, npm, npx, nvm:
$ node -v
v12.18.4
$ npm -v
6.14.6
$ nvm -v
0.36.0
$ npx -v
6.14.6
Installing passes well:
$ npm install
But trying to start it gives me following:
npm start
> [email protected] start /home/al/python/template/ui
> webpack-dev-server --open
ℹ 「wds」: Project is running at http://localhost:8080/
ℹ 「wds」: webpack output is served from /
ℹ 「wds」: Content not from webpack is served from /home/al/python/template/ui
ℹ 「wds」: 404s will fallback to /index.html
ℹ 「wdm」: wait until bundle finished: /
✖ 「wdm」: Hash: 11349b9868bb6765819a
Version: webpack 4.43.0
Time: 1755ms
Built at: 10/03/2020 1:21:37 PM
Asset Size Chunks Chunk Names
index.html 831 bytes [emitted]
main.js 396 KiB main [emitted] main
Entrypoint main = main.js
[0] multi (webpack)-dev-server/client?http://localhost:8080 ./src 40 bytes {main} [built]
[./node_modules/ansi-html/index.js] 4.24 KiB {main} [built]
[./node_modules/ansi-regex/index.js] 139 bytes {main} [built]
[./node_modules/html-entities/lib/index.js] 449 bytes {main} [built]
[./node_modules/loglevel/lib/loglevel.js] 8.43 KiB {main} [built]
[./node_modules/strip-ansi/index.js] 161 bytes {main} [built]
[./node_modules/webpack-dev-server/client/index.js?http://localhost:8080] (webpack)-dev-server/client?http://localhost:8080 4.29 KiB {main} [built]
[./node_modules/webpack-dev-server/client/overlay.js] (webpack)-dev-server/client/overlay.js 3.51 KiB {main} [built]
[./node_modules/webpack-dev-server/client/socket.js] (webpack)-dev-server/client/socket.js 1.53 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/createSocketUrl.js] (webpack)-dev-server/client/utils/createSocketUrl.js 2.91 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/log.js] (webpack)-dev-server/client/utils/log.js 964 bytes {main} [built]
[./node_modules/webpack-dev-server/client/utils/reloadApp.js] (webpack)-dev-server/client/utils/reloadApp.js 1.59 KiB {main} [built]
[./node_modules/webpack-dev-server/client/utils/sendMessage.js] (webpack)-dev-server/client/utils/sendMessage.js 402 bytes {main} [built]
[./node_modules/webpack/hot sync ^\.\/log$] (webpack)/hot sync nonrecursive ^\.\/log$ 170 bytes {main} [built]
[./src/index.jsx] 834 bytes {main} [built] [failed] [1 error]
+ 18 hidden modules
ERROR in ./src/index.jsx
Module build failed (from ./node_modules/babel-loader/lib/index.js):
SyntaxError: Unexpected token (13:4)
11 |
12 | render(
> 13 | <Provider store={store}>
| ^
14 | <App />
15 | </Provider>,
16 | document.getElementById('app')
Child html-webpack-plugin for "index.html":
1 asset
Entrypoint undefined = index.html
[./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 995 bytes {0} [built]
[./node_modules/lodash/lodash.js] 528 KiB {0} [built]
[./node_modules/webpack/buildin/global.js] (webpack)/buildin/global.js 470 bytes {0} [built]
[./node_modules/webpack/buildin/module.js] (webpack)/buildin/module.js 500 bytes {0} [built]
ℹ 「wdm」: Failed to compile.
[```
What did I do wrong?
I added the ability to specify multiple accounts to the fake back end. and added a role element
This was mainly so i could experiment with dynamic navigation rendering. It may be useful for others.
Its my first real javascript hack, mainly php and java/kotlin up to now. so be gentle. :-)
The code takes care of generating and verifying multiple unique fake jwt tokens.
The core of the get users code could do with moving to a separate function so that it can be used to authenticate more fake be urls.
===== fake-backend.js =======
export function configureFakeBackend() {
let users = [
{id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User', 'role': ["user"]},
{id: 2, username: 'admin', password: 'admin', firstName: 'Admin', lastName: 'User', 'role': ["admin", "user"]}
];
let realFetch = window.fetch;
window.fetch = function (url, opts) {
return new Promise((resolve, reject) => {
// wrap in timeout to simulate server api call
setTimeout(() => {
// authenticate
if (url.endsWith('/users/authenticate') && opts.method === 'POST') {
// get parameters from post request
let params = JSON.parse(opts.body);
// find if any user matches login credentials
let filteredUsers = users.filter(user => {
return user.username === params.username && user.password === params.password;
});
if (filteredUsers.length) {
// if login details are valid return user details and fake jwt token
let user = filteredUsers[0];
let responseJson = {
id: user.id,
username: user.username,
firstName: user.firstName,
lastName: user.lastName,
role: user.role,
token: 'fake-jwt-token-' + user.id
};
resolve({ok: true, text: () => Promise.resolve(JSON.stringify(responseJson))});
} else {
// else return error
reject('Username or password is incorrect');
}
return;
}
// get users
if (url.endsWith('/users') && opts.method === 'GET') {
// check for fake auth token in header and return users if valid, this security is implemented server side in a real application
if (opts.headers) {
let userid = Number(opts.headers.Authorization.replace(/^\D+/g, '')); // replace all leading non-digits with nothing
let found = false;
// Horribly inefficient linear search but allows the ids to be non sequential and sparse.
for (let i = 0; i < users.length; i++) {
if (users[i].id === userid) {
found = true;
break;
}
}
if (found && opts.headers.Authorization === ('Bearer fake-jwt-token-' + userid)) {
resolve({ok: true, text: () => Promise.resolve(JSON.stringify(users))});
return;
}
} // return 401 not authorised if token is null or invalid
reject('Unauthorised');
return;
}
// pass through any requests not handled above
realFetch(url, opts).then(response => resolve(response));
}, 500);
});
}
}
npm audit
is yielding a high vulnerability. I tried updating the dev-server to the recommended version, but it is not compatible with the current webpack.
=== npm audit security report ===
# Run npm install --save-dev [email protected] to resolve 1 vulnerability
SEMVER WARNING: Recommended action is a potentially breaking change
┌───────────────┬──────────────────────────────────────────────────────────────┐
│ High │ Missing Origin Validation │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Package │ webpack-dev-server │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Dependency of │ webpack-dev-server [dev] │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ Path │ webpack-dev-server │
├───────────────┼──────────────────────────────────────────────────────────────┤
│ More info │ https://nodesecurity.io/advisories/725 │
└───────────────┴──────────────────────────────────────────────────────────────┘
found 1 high severity vulnerability in 6418 scanned packages
1 vulnerability requires semver-major dependency updates.
Thanks in advance!
In the template's starter kit, there was no stand alone "Webpack.config.js" file and without it, I couldn't find a way to configure "apiURL" variable to integrate the real backend. It'd be more like a StackOverflow question but, is it possible to configure it via React.Scripts or any other way or I should add "Webpack.config.js" file as served like in the repo?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.