Comments (7)
Not sure, maybe a clumsy solution. But this rewrite of authProvider did the job for me:
import axios from 'axios';
import decodeJwt from 'jwt-decode';
import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_ERROR, AUTH_CHECK, AUTH_GET_PERMISSIONS } from 'react-admin';
export default (type, params) => {
// called when the user attempts to log in
if (type === AUTH_LOGIN) {
const { username, password } = params;
axios
.post('http://localhost:1337/auth/local', {
identifier: username,
password: password
})
.then(response => {
// Handle success.
localStorage.setItem('token', response.data.jwt);
localStorage.setItem('role', response.data.user.role.name);
console.log('Well done!');
console.log('User profile', response.data.user.role.name);
console.log('User token', response.data.jwt);
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error);
});
return localStorage.getItem('token') ? Promise.resolve() : Promise.reject();
}
// called when the user clicks on the logout button
if (type === AUTH_LOGOUT) {
localStorage.removeItem('token');
localStorage.removeItem('role');
return Promise.resolve();
}
// called when the API returns an error
if (type === AUTH_ERROR) {
const { status } = params;
if (status === 401 || status === 403) {
localStorage.removeItem('username');
return Promise.reject();
}
return Promise.resolve();
}
// called when the user navigates to a new location
if (type === AUTH_CHECK) {
return localStorage.getItem('token') ? Promise.resolve() : Promise.reject();
}
if (type === AUTH_GET_PERMISSIONS) {
const role = localStorage.getItem('role');
return role ? Promise.resolve(role) : Promise.reject();
}
return Promise.reject('Unknown method');
};
from ra-strapi-rest.
@e-ndrus I'm glad it was useful :)
So authProvider is not working for you because the Strapi Auth function accepts "identifier" as the name for the username.
To fix this issue, in your strapi project, go to plugins -> user-permissions -> controllers -> Auth.js
Then add this line
params.identifier = params.identifier ? params.identifier : params.username;
above the following if statement (line ~30)
if (!params.identifier) {
return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.email.provide' }] }] : 'Please provide your username or your e-mail.');
}
Final result
...
// The identifier is required.
params.identifier = params.identifier ? params.identifier : params.username;
if (!params.identifier) {
return ctx.badRequest(null, ctx.request.admin ? [{ messages: [{ id: 'Auth.form.error.email.provide' }] }] : 'Please provide your username or your e-mail.');
}
...
from ra-strapi-rest.
Thanks for the quick reply. Works like a charm. Except even though I am now logged in I can't see the posts in my content type. A message pops up "Forbidden". User permissions are set for all authenticated users. What am I doing wrong?
from ra-strapi-rest.
@e-ndrus Sweet!
Try logging in with an admin user. Authenticated role usually does not allow GET requests
Or create a new role and apply necessary permissions in the User-permissions plugin to the role, and assign that role to the user you want to use
from ra-strapi-rest.
Followed your advice, but no luck so far. I can access the documents only if user-permissions are set to public. Clearly I am missing something :(
from ra-strapi-rest.
Did you set up the httpClient for authProvider so that it sends the JWT token in the headers?
import React from 'react';
import { fetchUtils, Admin, Resource } from 'react-admin';
import simpleRestProvider from './ra-strapi-rest';
import authProvider from './authProvider'
import { PostList } from './posts';
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
}
const dataProvider = simpleRestProvider('http://localhost:1337', httpClient);
const App = () => (
<Admin authProvider={authProvider} dataProvider={dataProvider}>
<Resource name="posts" list={PostList} />
</Admin>
);
export default App;
from ra-strapi-rest.
@nazirov91 Thanks for your help. Yes, I set up everything exactly as above. When I try to log in, the following error is thrown: "Invalid token." It could be that my authProvider code is wrong. Posting below:
import { AUTH_LOGIN, AUTH_LOGOUT, AUTH_ERROR, AUTH_CHECK, AUTH_GET_PERMISSIONS } from 'react-admin';
export default (type, params) => {
// called when the user attempts to log in
if (type === AUTH_LOGIN) {
const { username, password } = params;
const request = new Request('http://localhost:1337/auth/local', {
method: 'POST',
body: JSON.stringify({ username, password }),
headers: new Headers({ 'Content-Type': 'application/json' }),
})
return fetch(request)
.then(response => {
if (response.status < 200 || response.status >= 300) {
throw new Error(response.statusText);
}
return response.json();
})
.then(({ token }) => {
localStorage.setItem('token', token);
});
}
return Promise.resolve();
// called when the user clicks on the logout button
if (type === AUTH_LOGOUT) {
localStorage.removeItem('token');
localStorage.removeItem('role');
return Promise.resolve();
}
// called when the API returns an error
if (type === AUTH_ERROR) {
const { status } = params;
if (status === 401 || status === 403) {
localStorage.removeItem('username');
return Promise.reject();
}
return Promise.resolve();
}
// called when the user navigates to a new location
if (type === AUTH_CHECK) {
return localStorage.getItem('token') ? Promise.resolve() : Promise.reject();
}
if (type === AUTH_GET_PERMISSIONS) {
const role = localStorage.getItem('role');
return role ? Promise.resolve(role) : Promise.reject();
}
return Promise.reject('Unknown method');
};
from ra-strapi-rest.
Related Issues (20)
- updated/alt auth example HOT 2
- Get Entire File Url HOT 6
- User model CORS error HOT 2
- TypeError: _dataProvider_server_rest__WEBPACK_IMPORTED_MODULE_3__.strapiDataProvider.getOne is not a function HOT 5
- Suggestion: Replace Content-Range HOT 1
- ImageInput causes CastError: Cast to ObjectId failed for value "[]" at path "avatar" HOT 3
- Unable to show data in ArrayField HOT 2
- ReferenceField not displaying data in List view HOT 1
- Has and belongs to many relation HOT 1
- Handle Strapi validation errors HOT 4
- Handle Strapi Components Show And Update HOT 8
- The dataProvider threw an error. It should return a rejected Promise instead.
- Add example for Relations to the Readme HOT 4
- N/A
- ImageInput causes CastError: Cast to ObjectId failed for value "[]" at path "avatar" HOT 1
- Strapi v4 is released HOT 4
- Single-Type Support HOT 1
- Fails with current version of strapi and react admin HOT 5
- No edit / or show buttons?
- Error for creating ressource HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from ra-strapi-rest.