React Flux APP验证
//文章原址:https://auth0.com/blog/2015/04/09/adding-authentication-to-your-react-flux-app/ A component is just a function 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 constructor() { this.state = { user: ‘’,password: ‘’ }; } // This will be called when the user clicks on the login button 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 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 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() // 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 }); } 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. 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. return this._user; } get jwt() { return this._jwt; } isLoggedIn() { return !!this._user; } 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 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} /> ); } } 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. // Here,we display the user information return (<h1>Hello {this.props.user.username}</h1>); } 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 method: ‘GET’,headers: { Authorization: ‘Bearer ‘ + this.props.jwt } } 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 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! :). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- swift – 带有私有构造函数的公共OptionSet
- objective-c – 使自定义类型出现在Xcode的文档弹
- ajax(iframe)无刷新提交表单、上传文件
- ruby-on-rails – 如何使用ruby方法.present?
- 5-create-react-app整合antDesign功能
- xml – rdf:resource,rdf:about和rdf:ID之间的
- 【SQLAlchemy】PostgreSQL的自增长主键定义
- 详解正则表达式以及文本处理工具—grep、egrep的
- 使用Sqlite3与Python 2.7将数据库添加到Django项
- ruby-on-rails – Ruby on Rails:创建子对象