javascript - User Authentication for API from React App -
i have simple api built in nodal allows user create new job (essentially work order service business). api using oauth, in order create new job, user has first obtain token authenticating via username , password.
the frontend going built in react. in order access site, user have log in username , password, @ point they'll given token make api calls. 2 questions:
1) how securely store api token such user doesn't have log in every time page refreshes?
2) how use same login step determine if have access given page within frontend app?
this process have used in current project. when user logs in, take token , store in localstorage. every time user goes route, wrap component route serves in hoc. here code hoc checks token.
export function requireauthentication(component) { class authenticatedcomponent extends react.component { componentwillmount () { this.checkauth(this.props.user.isauthenticated); } componentwillreceiveprops (nextprops) { this.checkauth(nextprops.user.isauthenticated); } checkauth (isauthenticated) { if (!isauthenticated) { let redirectafterlogin = this.props.location.pathname; browserhistory.push(`/login?next=${redirectafterlogin}`); } } render () { return ( <div> {this.props.user.isauthenticated === true ? <component {...this.props}/> : null } </div> ) } } const mapstatetoprops = (state) => ({ user: state.user }); return connect(mapstatetoprops)(authenticatedcomponent); }
then in index.js wrap each protected route hoc so:
<route path='/protected' component={requireauthentication(protectedcomponent)} />
this how user reducer looks.
export default function userreducer(state = {}, action) { switch(action.type) { case types.user_login_success: return {...action.user, isauthenticated: true}; default: return state; } }
action.user contains token. token can either come api when user first logs in, or localstorage if user logged in user.
Comments
Post a Comment