React + JWT p2


FastAPI
Simple OAuth2 with Password and Bearer
につなげてテストする。

 

index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import UsersMe from './UsersMe';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <UsersMe />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

Login.tsx

import React, { useState } from 'react';
import UsersMe from './UsersMe';

const Login = () => {
    const [user, setUser] = useState({username: '', password: ''});
    const [isAuthenticated, setAuth] = useState(false);

    const handleChange = (event : any) => {
        setUser({...user, [event.target.name] : event.target.value})
    }

    const login = () => {
        console.log(JSON.stringify(user));
        fetch("http://127.0.0.1:8000/token", 
        {
            method : "POST",
            headers : {
                'Content-Type' : 'application/x-www-form-urlencoded'
            },
            body: `username=${user.username}&password=${user.password}`
        })
        .then(response => response.json())
        .then(responseJSON => {
            const access_token = responseJSON.access_token;
            if (access_token !== null) {
                sessionStorage.setItem("access_token", access_token);
                setAuth(true);
            }
        })
        .catch(error => {
            console.error(error);
        })
    }

    if (isAuthenticated) {
        return(
            <div>
                <UsersMe />
            </div>  
        );
    }
    else {
        return(
            <div>
                <input type="text" name="username" onChange={handleChange} /><br />
                <input type="password" name="password" onChange={handleChange} /><br />
                <button onClick={login}>Login</button>
            </div>
        );
    }

}

export default Login;

UsersMe.tsx

import React, { useLayoutEffect, useState } from 'react';
import Login from './Login';
import UsersMeItem from './UsersMeItems';

const UsersMe = () => {
    const [userInfo, setUserInfo] = useState("");
    const [isAuthenticated, setAuth] = useState(false);

    useLayoutEffect(() => {
        users_me();
    });

    const users_me = () => {
        const access_token = sessionStorage.getItem("access_token");
        fetch("http://localhost:8000/users/me",
        {
            method : "GET",
            headers : {
                'Authorization' : 'Bearer ' + access_token
            },
        })
        .then(response => {
            if (response.status === 200) {
                setAuth(true);
                return response.json();
            }
            sessionStorage.setItem("access_token", "");
            setAuth(false);
            return null;
        })
        .then(responseJSON => {
            if (responseJSON) {
                setUserInfo(JSON.stringify(responseJSON));
            }
        })
        .catch(error => {
            console.error(error);
        })
    }

    const logout = () => {
        sessionStorage.setItem("access_token", "");
        setAuth(false);
    }

    if (isAuthenticated) {
        return(
            <div>
                Me : {userInfo} 
                <UsersMeItem /> 
                <button onClick={logout}>Logout</button>
            </div>
        );
    }
    else {
        return(
            <div>
                <Login />
            </div>
        );
    }
}

export default UsersMe;

UsersMeItems.tsx

import React, { useLayoutEffect, useState } from 'react';

const UsersMeItem = () => {
    const [itemInfo, setItemInfo] = useState("");

    useLayoutEffect(() => {
        users_me_item();
    });

    const users_me_item = () => {
        const access_token = sessionStorage.getItem("access_token");
        fetch("http://localhost:8000/users/me/items",
        {
            method : "GET",
            headers : {
                'Authorization' : 'Bearer ' + access_token
            },
        })
        .then(response => {
            if (response.status === 200) {
                return response.json();
            }
            return null;
        })
        .then(responseJSON => {
            if (responseJSON) {
                setItemInfo(JSON.stringify(responseJSON));
            }
        })
        .catch(error => {
            console.error(error);
        })
    }

    return(
        <div>
            Item : {itemInfo}
        </div>
    );
}

export default UsersMeItem;

 

 

投稿日: