Tạo Authentication cho app React trong 5 phút

4 min


1047
1.5k shares, 1047 points

Lời giới thiệu

Hôm nay, tôi sẽ chỉ cho bạn cách bạn có thể thêm authentication(xác thực) đơn giản vào ứng dụng React của mình bằng cách sử dụng xác thực từ Okta. Một hệ thống quản lý người dùng có thể được sử dụng trên nhiều ứng dụng, nhiều ngôn ngữ hoặc framework

Sign-Up

Trước khi có thể tích hợp Okta vào ứng dụng react. Bạn cần có tài khoản nhà phát triển Okta. Vì vậy, hãy tiếp tục và tạo tài khoản miễn phí của bạn ngay bây giờ.

Free Okta Developer Account

Okta Dashboard

Sau khi tạo tài khoản miễn phí, bạn sẽ được chuyển hướng đến trang dashboard. Bạn có nhận thấy Org URLtrong trang dashboard. Bạn cần điều đó cho ứng dụng của mình. Trang dashboard cũng có chỉ số người dùng và nhật ký hệ thống hiển thị tất cả các hoạt động.

okta dashboard

Đăng ký App React

Đã đến lúc đăng ký ứng dụng react. Nhấp vào liên kết Applications  trên trang dashboard.

  • Click chọn Add Application
  • Tiếp tục chọnSingle Page App
  • Thêm tên app vào Name field

Bây giờ, bạn phải chỉnh sửa field URI cơ sở. Tôi sẽ giả định rằng bạn đang sử dụng ứng dụng tạo trên server local của mình.

http://localhost:3000

Làm điều tương tự với URI chuyển hướng Đăng nhập & Nhấp vào Done

http://localhost:3000/implicit/callback

Bây giờ ứng dụng của bạn đã được đăng ký và bạn sẽ nhận được Client ID
 

Khởi động IDE

  • Điều hướng đến thư mục app react của bạn
  • Thêm các package cần thiết
yarn add react-router-dom @okta/okta-react @okta/signin-widget

Vì lợi ích của ví dụ này, hãy giả sử rằng ứng dụng react của bạn có ba trang nằm trong các route riêng tư. Và chỉ người dùng được authorized(ủy quyền) mới có quyền truy cập vào các route.

/home /user /order

Tạo component Login app React

Create a new folder called auth in your components folder and create a new file called Login.js with the following code.

Tạo một thư mục mới được gọi là auth trong thư mục components và tạo một tệp mới có tên là Login.js với code sau.

import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import OktaSignInWidget from './SigninWidget';
import { withAuth } from '@okta/okta-react';
export default withAuth(class Login extends Component {
  constructor(props) {
    super(props);
    this.state = {
      authenticated: null
    };
    this.checkAuthentication();
  }
  async checkAuthentication() {
    const authenticated = await this.props.auth.isAuthenticated();
    if (authenticated !== this.state.authenticated) {
      this.setState({ authenticated });
      this.props.history.push('/home')
    }
  }
 componentDidUpdate() {
    this.checkAuthentication();
  }
  onSuccess = (res) => {
    if (res.status === 'SUCCESS') {
      return this.props.auth.redirect({
        sessionToken: res.session.token
      });
   } else {
    // The user can be in another authentication state that requires further action.
    // For more information about these states, see:
    //   https://github.com/okta/okta-signin-widget#rendereloptions-success-error
    }
  }
  onError = (err) => {
    console.log('error logging in', err);
  }
render() {
    if (this.state.authenticated === null) return null;
    return this.state.authenticated ?
      <Redirect to={{ pathname: '/' }}/> :
      <OktaSignInWidget
        baseUrl={this.props.baseUrl}
        onSuccess={this.onSuccess}
        onError={this.onError}/>;
  }
});

Tiếp theo, bạn cần tạo một tệp mới có tên SigninWidget trong cùng thư mục auth với code sau.

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import OktaSignIn from '@okta/okta-signin-widget';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
 class SigninWidget extends Component {
  componentDidMount() {
    const el = ReactDOM.findDOMNode(this);
    this.widget = new OktaSignIn({
      baseUrl: this.props.baseUrl,
      authParams: {
        pkce: true
      },
    });
    this.widget.renderEl({el}, this.props.onSuccess, this.props.onError);
  }
  componentWillUnmount() {
    this.widget.remove();
  }
  render() {
    return <div />;
  }
};
export default SigninWidget

Bước tiếp theo là cập nhật tệp route. Đây là một ví dụ từ việc implement Okta. Bao bọc các route riêng tư bên trong component SecureRoute và cũng thay thế Clientissuer  bằng thông tin đăng nhập của riêng bạn từ bảng điều khiển dành cho nhà phát triển Okta..

import React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Order from "./pages/Order.js";
import Home from "./pages/Home.js";
import Users from "./pages/Users.js";
import Login from "./components/auth/Login";
import { Security, SecureRoute, ImplicitCallback } from "@okta/okta-react";
function onAuthRequired({ history }) {
  history.push("/login");
}
const AppRoute = () => (
  <Router>
    <Security
      issuer="https://dev-944example.okta.com/oauth2/default" //Replace with your ORG URI.
      clientId="0oa1ws12avokObj45C357example" //Replace with your own client id
      redirectUri={window.location.origin + "/implicit/callback"}
      onAuthRequired={onAuthRequired}
    >
      <SecureRoute exact path="/orders" component={Order} />
      <SecureRoute exact path="/users" component={Users} />
      <Route exact path="/" component={Home} />
      <Route
        path="/login"
        render={() => <Login baseUrl="https://dev-968924.okta.com" />}
      />
      <Route path="/implicit/callback" component={ImplicitCallback} />
    </Security>
  </Router>
);
export default AppRoute;

Tạo hàm Logout cho app React

Đây là bước cuối cùng. Bạn sẽ muốn tạo nút đăng xuất trong tệp home.js hoặc tệp gốc của mình. Nút này được hiển thị cho người dùng sau khi đăng nhập và đừng quên bọc chức năng bên trong withAuth để sử dụng các đạo cụ xác thực.

import { withAuth } from "@okta/okta-react";
import Breadcrumb from './breadcrumb.js'
class Home extends Component {
  logout = async () => {
    this.props.auth.logout("/");
  };
  render() {
    return (
      <>
        <Breadcrumb home="Logout" click={this.logout} />
      </>
    );
  }
}
export default withAuth(Home);

Kết luận

Chúng ta đã tạo được authentication cho appReact. Tôi hy vọng bạn đã tích hợp thành công xác thực Okta trong app react của mình. Nếu bạn gặp bất kỳ rắc rối nào, hãy bình luận bên dưới. Tôi sẽ giúp bạn giải quyết nó.

Tham khảo thêm về React tại đây: Cách xây dựng Micro Frontend với React và SSR


Like it? Share with your friends!

1047
1.5k shares, 1047 points

What's Your Reaction?

hate hate
1
hate
confused confused
3
confused
fail fail
2
fail
fun fun
2
fun
geeky geeky
2
geeky
love love
6
love
lol lol
1
lol
omg omg
1
omg
win win
2
win