React Flux APP验证

//文章原址:https://auth0.com/blog/2015/04/09/adding-authentication-to-your-react-flux-app/
//记录一下,有空翻一下
Let’s face it. React is the new cool kid on the block. Everybody is working on creating React components because it entails understanding just 2 basic concepts:

A component is just a function
Single-direction data flow
However,once you start creating a bigger app,you realize that just using React isn’t enough. So you start looking at Flux,which is the architecture Facebook uses to create React apps.

As we learned in a previous blog post,learning how to conduct authentication in a Single Page App can get super complex. We had to learn about tokens,JWTs and how to integrate them with SPAs. Learning how to do it with Flux is even harder! That’s why in this blogpost we’ll learn how to add authentication to a React Flux app.

Image

Before we start

We’ll be coding our React app using ES6 thanks to Browserify and Babelify,and we’ll be using npm for build tools and installing dependencies. If you want to start a project with the same architecture,just clone this seed project.

Let’s code!

Login page

THE LOGIN COMPONENT

Login Component

First,let’s create our Login component. Its main function is rendering an input for the username and password and calling the AuthService when the user clicks on the login button.

// ... imports
export default class Login extends React.Component {

constructor() {

this.state = {
  user: ‘’,password: ‘’
};

}

// This will be called when the user clicks on the login button
login(e) {

e.preventDefault();
// Here,we call an external AuthService. We’ll create it in the next step
Auth.login(this.state.user,this.state.password)
  .catch(function(err) {
    console.log(“Error logging in”,err);
  });

}

render() {

return (
    <form role=“form”>
    <div className=“form-group”>
      <input type=“text” valueLink={this.linkState(‘user’)}placeholder=“Username” />
      <input type=“password” valueLink={this.linkState(‘password’)} placeholder=“Password” />
    </div>
    <button type=“submit” onClick={this.login.bind(this)}>Submit</button>
  </form>
</div>
);

}
}

// We’re using the mixin LinkStateMixin to have two-way databinding between our component and the HTML.
reactMixin(Login.prototype,React.addons.LinkedStateMixin);
THE AUTHSERVICE & THE LOGINACTION

Authseervice and login action

Our AuthService is in charge of calling our login API. The server will validate the username and password and return a token (JWT) back to our app. Once we get it,we’ll create a LoginAction and send it to all the Stores using the Dispatcher from Flux.

// AuthService.js
// ... imports
class AuthService {

login(username,password) {

// We call the server to log the user in.
return when(request({
  url: ‘http://localhost:3001/sessions/create',method: ‘POST’,crossOrigin: true,type: ‘json’,data: {
    username,password
  }
}))
.then(function(response) {
    // We get a JWT back.
    let jwt = response.id_token;
    // We trigger the LoginAction with that JWT.
    LoginActions.loginUser(jwt);
    return true;
});

}
}

export default new AuthService()
// LoginAction.js
// ... imports
export default {
loginUser: (jwt) => {

// Go to the Home page once the user is logged in
RouterContainer.get().transitionTo(‘/‘);
// We save the JWT in localStorage to keep the user authenticated. We’ll learn more about this later.
localStorage.setItem(‘jwt’,jwt);
// Send the action to all stores through the Dispatcher
AppDispatcher.dispatch({
  actionType: LOGIN_USER,jwt: jwt
});

}
}
You can take a look at the router configuration on Github,but it’s important to note that once the LoginAction is triggered,the user is successfully authenticated. Therefore,we need to redirect him or her from the Login page to the Home. That’s why we’re adding the URL transition in here.

THE LOGINSTORE

Dispatcher and LoginStore

The LoginStore,like any other store,has 2 functions:

It holds the data it gets from the actions. In our case,that data will be used by all components that need to display the user information.
It inherits from EventEmmiter. It’ll emit a change event every time its data changes so that Components can be rendered again.
// ... imports
class LoginStore extends BaseStore {

constructor() {

// First we register to the Dispatcher to listen for actions.
this.dispatchToken = AppDispatcher.register(this._registerToActions.bind(this));
this._user = null;
this._jwt = null;

}

_registerToActions(action) {

switch(action.actionType) {
  case USER_LOGGED_IN:
    // We get the JWT from the action and save it locally.
    this._jwt = action.jwt;
    // Then we decode it to get the user information.
    this._user = jwt_decode(this._jwt);
    // And we emit a change to all components that are listening.
    // This method is implemented in the `BaseStore`.
    this.emitChange();
    break;
  default:
    break;
};

}

// Just getters for the properties it got from the action.
get user() {

return this._user;

}

get jwt() {

return this._jwt;

}

isLoggedIn() {

return !!this._user;

}
}
export default new LoginStore();
You can take a look at the BaseStore in Github. It includes some utility methods that all stores will have.
Displaying the user information

CREATING AN AUTHENTICATED COMPONENT

AuthenticatedComponent

Now,we can start creating components that require authentication. For that,we’ll create a wrapper (or decorator) component called AuthenticatedComponent. It’ll make sure the user is authenticated before displaying its content. If the user isn’t authenticated,it’ll redirect him or her to the Login page. Otherwise,it’ll send the user information to the component it’s wrapping:

// ... imports
export default (ComposedComponent) => {
return class AuthenticatedComponent extends React.Component {

static willTransitionTo(transition) {
  // This method is called before transitioning to this component. If the user is not logged in,we’ll send him or her to the Login page.
  if (!LoginStore.isLoggedIn()) {
    transition.redirect(‘/login’);
  }
}

constructor() {
  this.state = this._getLoginState();
}

_getLoginState() {
  return {
    userLoggedIn: LoginStore.isLoggedIn(),user: LoginStore.user,jwt: LoginStore.jwt
  };
}

// Here,we’re subscribing to changes in the LoginStore we created before. Remember that the LoginStore is an EventEmmiter.
componentDidMount() {
  LoginStore.addChangeListener(this._onChange.bind(this));
}

// After any change,we update the component’s state so that it’s rendered again.
_onChange() {
  this.setState(this._getLoginState());
}

componentWillUnmount() {
    LoginStore.removeChangeListener(this._onChange.bind(this));
}

render() {
  return (
  <ComposedComponent
    {...this.props}
    user={this.state.user}
    jwt={this.state.jwt}
    userLoggedIn={this.state.userLoggedIn} />
  );
}

}
};
An interesting pattern is used here. First,take a look at what we’re exporting. We’re exporting a function that receives a Component as a parameter and then returns a new Component that wraps the one that was sent as an argument. Next,take a look at the render method. There,we’re rendering the Component we received as a parameter. Besides the props it should receive,we’re also sending it all the user information so it can use those properties. Now,let’s create the Home component which will be wrapped by the AuthenticatedComponent we’ve just created.

HOME PAGE

Home

The Home will display user information. As it’s wrapped by the AuthenticatedComponent,we can be sure of 2 things:

Once the render method is called on the Home component,we know the user is authenticated. Otherwise,the app would have redirected him to the Login page.
We know we’ll have the user information under props because we’ve received them from the AuthenticatedComponent
// ... imports
// We’re wrapping the home with the AuthenticatedComponent
export default AuthenticatedComponent(class Home extends React.Component {
render() {

// Here,we display the user information
return (<h1>Hello {this.props.user.username}</h1>);

}
});
Let’s call an API!

Now,you should be able to call an API. In order to call an API that requires authentication,you must send the JWT we received on Login in the Authorization header. Any AuthenticatedComponent has access to this JWT so you can do something as follows:

// Home.jsx
// It must be on an AuthenticatedComponent
callApi() {
fetch(‘http://example.com/my-cool-url',{

method: ‘GET’,headers: {
  Authorization: ‘Bearer ‘ + this.props.jwt
}

}
Keeping the user authenticated

Now that the user is authenticated,we want to keep him or her authenticated instead of showing the login page every time he refreshes the website. Due to the fact we’re saving the JWT on localStorage after a successful authentication,we can manually trigger the LoginAction and everything will work. That’s the beauty of using Flux.

// app.jsx ==> Bootstrap file
let jwt = localStorage.getItem(‘jwt’);
if (jwt) {
LoginActions.loginUser(jwt);
}
Aside: Using React with Auth0

Auth0 issues JSON Web Tokens on every login for your users. That means that you can have a solid identity infrastructure,including Single Sign On,User Management,support for Social (Facebook,Github,Twitter,etc.),Enterprise (Active Directory,LDAP,SAML,etc.) and your own database of users with just a few lines of code. We implemented a tight integration with React. You can read the documentation here or you can checkout the Github example

Closing remarks

We’ve finished implementing the Login for a React Flux app. If you want to know how to implement a signup or if you want to see the full example at work,you can grab the code from Github.

Happy Hacking! :).

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如果组件之中有复用的代码,需要重新创建一个父类,父类中存储公共代码,返回子类,同时把公用属性...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例如我们的 setState 函数式同步执行的,我们的事件处理直接绑定在了 dom 元素上,这些都跟 re...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom 转为真实 dom 进行挂载。其实函数是组件和类组件也是在这个基础上包裹了一层,一个是调...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使用,可能是不了解。我公司的项目就没有使用,但是在很多三方库中都有使用。本小节我们来学习下如果使用该...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接触 react 就一直使用 mobx 库,上手简单不复杂。
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc 端可以使用分页进行渲染数限制,在移动端可以使用下拉加载更多。但是对于大量的列表渲染,特别像有实时数据...
本小节开始前,我们先答复下一个同学的问题。上一小节发布后,有小伙伴后台来信问到:‘小编你只讲了类组件中怎么使用 ref,那在函数式组件中怎么使用呢?’。确实我们...
上一小节我们了解了固定高度的滚动列表实现,因为是固定高度所以容器总高度和每个元素的 size、offset 很容易得到,这种场景也适合我们常见的大部分场景,例如...
上一小节我们处理了 setState 的批量更新机制,但是我们有两个遗漏点,一个是源码中的 setState 可以传入函数,同时 setState 可以传入第二...
我们知道 react 进行页面渲染或者刷新的时候,会从根节点到子节点全部执行一遍,即使子组件中没有状态的改变,也会执行。这就造成了性能不必要的浪费。之前我们了解...
在平时工作中的某些场景下,你可能想在整个组件树中传递数据,但却不想手动地通过 props 属性在每一层传递属性,contextAPI 应用而生。
楼主最近入职新单位了,恰好新单位使用的技术栈是 react,因为之前一直进行的是 vue2/vue3 和小程序开发,对于这些技术栈实现机制也有一些了解,最少面试...
我们上一节了了解了函数式组件和类组件的处理方式,本质就是处理基于 babel 处理后的 type 类型,最后还是要处理虚拟 dom。本小节我们学习下组件的更新机...
前面几节我们学习了解了 react 的渲染机制和生命周期,本节我们正式进入基本面试必考的核心地带 -- diff 算法,了解如何优化和复用 dom 操作的,还有...
我们在之前已经学习过 react 生命周期,但是在 16 版本中 will 类的生命周期进行了废除,虽然依然可以用,但是需要加上 UNSAFE 开头,表示是不安...
上一小节我们学习了 react 中类组件的优化方式,对于 hooks 为主流的函数式编程,react 也提供了优化方式 memo 方法,本小节我们来了解下它的用...
开源不易,感谢你的支持,❤ star me if you like concent ^_^
hel-micro,模块联邦sdk化,免构建、热更新、工具链无关的微模块方案 ,欢迎关注与了解
本文主题围绕concent的setup和react的五把钩子来展开,既然提到了setup就离不开composition api这个关键词,准确的说setup是由...
ReactsetState的执行是异步还是同步官方文档是这么说的setState()doesnotalwaysimmediatelyupdatethecomponent.Itmaybatchordefertheupdateuntillater.Thismakesreadingthis.staterightaftercallingsetState()apotentialpitfall.Instead,usecom