Spring + RESTful + JWTへReactからログインする。
Login.js
import React, { useState } from 'react'; import Hello from './Hello'; const Login = () => { const [user, setUser] = useState({username: '', password: ''}); const [isAuthenticated, setAuth] = useState(false); const handleChange = (event) => { setUser({...user, [event.target.name] : event.target.value}) } const login = () => { fetch("http://localhost:8080/login", { method : "POST", headers : { 'Content-Type' : 'application/json' }, body: JSON.stringify(user) }) .then(response => response.json()) .then(responseJSON => { const jwttoken = responseJSON.token; if (jwttoken !== null) { sessionStorage.setItem("jwttoken", jwttoken); setAuth(true); } }) .catch(error => console.error(error)) } if (isAuthenticated) { return( <div> <Hello /> </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;
Hello.js
import React, { useLayoutEffect, useState } from 'react'; import Login from './Login'; const Hello = () => { const [greeting, setGreeting] = useState(""); const [isAuthenticated, setAuth] = useState(false); useLayoutEffect(() => { hello(); }); const hello = () => { const jwttoken = sessionStorage.getItem("jwttoken"); fetch("http://localhost:8080/hello", { method : "POST", headers : { 'Authorization' : 'Bearer ' + jwttoken }, }) .then(response => { if (response.status === 200) { setAuth(true); return response.json(); } sessionStorage.setItem("jwttoken", ""); setAuth(false); return null; }) .then(responseJSON => { if (responseJSON) { setGreeting(responseJSON.greeting); } }) .catch(error => console.error(error)) } if (isAuthenticated) { return( <div> From Server : {greeting} </div> ); } else { return( <div> <Login /> </div> ); } } export default Hello;