개발자

백엔드 연결없이 로그인 회원가입

2022년 12월 16일조회 1,754

JWT로 로그인 회원가입을 공부하는 중인데 백엔드가 없어가지고 .. 혹시 혼자서도 axios로 연습해볼 수 있나요??? 어떻게 하나요.??? 아 참고로 파이어베이스는 제외요!

이 질문이 도움이 되었나요?
'추천해요' 버튼을 누르면 좋은 질문이 더 많은 사람에게 노출될 수 있어요. '보충이 필요해요' 버튼을 누르면 질문자에게 질문 내용 보충을 요청하는 알림이 가요.
profile picture
익명님의 질문

답변 2

안철진님의 프로필 사진

cloudflare의 worker는 어떠신가요?

황민호님의 프로필 사진

백엔드가 없으면 사용자를 완전히 인증하는 것은 불가능 합니다. 그 이유는 인증에 사용되는 JWT(JSON Web Token)가 변조되지 않았는지 확인하기 위해 신뢰할 수 있는 엔터티(예: 서버)에서 확인해야 하기 때문입니다. 서버 없이 사용자 인증을 연습하고 싶다면 모의 서버나 json-server와 같은 서버 에뮬레이터를 사용할 수 있습니다. 이렇게 하면 JWT의 서버측 확인을 시뮬레이션할 수 있으므로 인증된 요청을 만들고 응답을 처리하는 연습을 할 수 있습니다. 또는 jsjwt와 같은 브라우저 기반 JWT 라이브러리를 사용하여 클라이언트 측에서 JWT에 서명하고 확인할 수도 있습니다. 이를 통해 서버 없이 JWT 작업을 연습할 수 있지만 JWT 서명에 사용된 비밀 키가 클라이언트에 노출되어 잠재적으로 리스크를 갖고 있습니다. 아래는 Axios와 JWT를 사용하여 사용자를 인증하는 예제입니다. 1. 먼저 비밀 키로 JSON 개체에 서명하여 JSON 웹 토큰(JWT)을 만듭니다. const jwt = require('jsonwebtoken'); const payload = { userId: 123, email: 'user@example.com' }; const secretKey = 'my-secret-key'; const token = jwt.sign(payload, secretKey); 2. 다음으로 요청 헤더에 JWT가 있는 서버에 POST 요청을 보내는 Axios 클라이언트를 만듭니다. axios.post()다음 방법을 사용합니다. const axios = require('axios'); axios.post('http://example.com/login', {}, { headers: { 'Authorization': `Bearer ${token}` } }) .then(response => { // handle success }) .catch(error => { // handle error }); 3. 서버 측에서 POST 요청을 수락하고 비밀 키를 사용하여 JWT를 확인하는 경로를 만듭니다. JWT가 유효한 경우 서버는 사용자가 인증되었음을 나타내는 응답을 반환해야 합니다. JWT가 유효하지 않으면 서버에서 오류를 반환해야 합니다. const jwt = require('jsonwebtoken'); app.post('/login', (req, res) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (!token) { return res.status(401).send({ error: 'Unauthorized' }); } jwt.verify(token, secretKey, (error, user) => { if (error) { return res.status(401).send({ error: 'Unauthorized' }); } res.send({ authenticated: true }); }); }); 4. Axios 클라이언트에서 상태 코드를 확인하여 서버의 응답을 처리합니다. 상태 코드가 성공(예: 200)을 나타내면 사용자가 인증된 것으로 간주할 수 있습니다. 상태 코드가 오류(예: 401)를 나타내면 사용자가 인증되지 않은 것으로 간주할 수 있습니다. axios.post('http://example.com/login', {}, { headers: { 'Authorization': `Bearer ${token}` } }) .then(response => { if (response.status === 200) { console.log('User is authenticated'); } else { console.log('User is not authenticated'); } }) .catch(error => { console.error(error); }); 아래는 Node.js와 Express로 구현된 서버 측 전체 코드입니다. const express = require('express'); const jwt = require('jsonwebtoken'); const app = express(); const secretKey = 'my-secret-key'; app.post('/login', (req, res) => { // Get the JWT from the request header const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; // If the JWT is not provided, return an error if (!token) { return res.status(401).send({ error: 'Unauthorized' }); } // Verify the JWT using the secret key jwt.verify(token, secretKey, (error, user) => { // If the JWT is invalid, return an error if (error) { return res.status(401).send({ error: 'Unauthorized' }); } // If the JWT is valid, send a response indicating that the user is authenticated res.send({ authenticated: true }); }); }); app.listen(3000, () => { console.log('Server listening on port 3000'); });

황민호님의 프로필 사진

황민호

Kakao General Developer2022년 12월 18일

클라이언트 전체 코드입니다. const axios = require('axios'); const jwt = require('jsonwebtoken'); const secretKey = 'my-secret-key'; // Sign a JSON object with the secret key to create a JWT const payload = { userId: 123, email: 'user@example.com' }; const token = jwt.sign(payload, secretKey); // Send a POST request to the server with the JWT in the request header axios.post('http://example.com/login', {}, { headers: { 'Authorization': `Bearer ${token}` } }) .then(response => { // If the status code indicates success, the user is authenticated if (response.status === 200) { console.log('User is authenticated'); } else { console.log('User is not authenticated'); } }) .catch(error => { console.error(error); });

지금 가입하면 모든 질문의 답변을 볼 수 있어요!

현직자들의 명쾌한 답변을 얻을 수 있어요.

또는

이미 회원이신가요?

목록으로
키워드로 질문 모아보기

실무, 커리어 고민이 있다면

새로운 질문 올리기

지금 가입하면 모든 질문의 답변을 볼 수 있어요!