1
2

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でログイン機能

1
Posted at

はじめに

Reactでとてもシンプルなログイン機能を見つけたのでメモです。localstrageにトークンを持たせる実装なので、XSSによる脆弱性が考えられます。あくまで一例として読んでいただければ幸いです。

実装

localStorageを用いてログイン情報を管理します。ログインしてない状態でURLにアクセスしたときにログイン画面にリダイレクトするために、PrivateRouteというコンポーネントを作成し、App.jsのRouteに設置します。

Login.js
// 省略
if (パスワードが一致) {
  localStorage.setItem('user_id', トークン);
}
// 省略

api側でmailadressとpasswordが一致したら、localStrageにトークンを設置する。
ログアウトの際は、localStorage.removeItem('user_id')をする。

PrivateRoute.js
  
import React from "react";
import { Route, Redirect } from "react-router-dom";

function PrivateRoute(props) {
    var isAuth = false;  
    var  user_id= localStorage.getItem("user_id");
    if(user_id!=null){        
        isAuth = true;
    }
    return isAuth ? <Route {...props} /> : <Redirect to="/login" />;
}

export default PrivateRoute;

localStrageにトークンが存在すれば遷移先のRouteを、存在しなければログインページへのリダイレクトをする。

App.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import Login from "./login/login";
import Home from "./home/home";
import PrivateRoute from "./components/PrivateRoute";

class App extends React.Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
          <PrivateRoute exact path="/home" component={Home} />
          <Route exact path="/login" component={Login} />
        </Switch>
      </BrowserRouter>
    );
  }
}

export default App;

<Route>はログインしなくても見れるページ、<PrivateRoute>はログインしないと見れないページに使用します。

おわりに

結局、セキュリティの面も考慮した一番良い方法は何なのでしょうか。Cookieなどに持たせるべきなのでしょうか。

1
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?