1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

React+ReduxアプリにNode.js(express)とJWTで認証・認可周りの処理を実装する③ルート保護

1
Last updated at Posted at 2020-04-29

はじめに

前回の続きで、今回はReact+Reduxアプリケーションのフロント側のルート保護についての内容を書いていきます。

プライベートルート保護のコンポーネントを作る

ローカルストレージにトークンが保存されていなかったら、ログイン画面にリダイレクトするイメージで実装しています。

src/components/privateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";

export const PrivateRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest}
    render={(props) =>
      localStorage.getItem("token") ? (
        <Component {...props} />
      ) : (
        <Redirect to={{ pathname: "/", state: { from: props.location } }} />
      )
    }
  />
);

プライベートルート保護のコンポーネントを適用する

[src/components/privateRoute.js]をインポートして、トップ画面のルートを[PrivateRoute]に変更します。

src/index.js
import { PrivateRoute } from "./components/privateRoute";

ReactDOM.render(
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        <Route path="/login" component={Login} />
        <PrivateRoute path="/top" component={TopPage} />
        <Route path="/" component={Login} />
      </Switch>
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

まとめ

これでトップ画面に直接URL(/top)をたたいても遷移しなくなりました。
以上でReact+ReduxアプリにNode.js(express)とJWTで認証・認可周りの処理の実装が完了しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?