새로운 애플리케이션을 생성해주면 My Applications에 어플이 생성됩니다.
OAuth2 인증 절차에서 리다이렉션 URI를 설정하는 것에 관한 정보입니다.
OAuth2 인증 절차는 보통 아래와 같이 이루어집니다:
- 사용자가 애플리케이션에서 '로그인' 버튼을 클릭합니다.
- 사용자는 디스코드 인증 페이지로 리다이렉트됩니다.
- 사용자가 애플리케이션에 대한 접근을 승인합니다.
- 디스코드는 사용자를 애플리케이션의 리다이렉션 URI로 다시 리다이렉트합니다. 이 때, 인증 코드가 URI의 쿼리 파라미터로 포함되어 있습니다.
- 애플리케이션은 이 인증 코드를 받아 인증 토큰을 얻습니다.
리다이렉션 URI는 사용자를 애플리케이션으로 다시 리다이렉트하기 위한 주소입니다. 이 URI는 사용자가 애플리케이션에 대한 접근을 승인한 후에 디스코드가 사용자를 다시 보내기 위한 위치를 결정합니다.
1.사용자명과 , 아바타 , 이메일을 선택하였습니다.
2.Redirects 만들어두었던 주소를 선택하고
3. 최종 url 이 생성됩니다.
로그인 버튼을 클릭시 이렇게 화면에 출력됩니다.
import React from 'react';
const DiscordLoginButton = () => {
const discordLogin = async () => {
const url = `만들어둔 최종 url을 넣어줍니다.`;
// 사용자를 Discord 로그인 페이지로 리디렉션합니다.
window.location.href = url;
// URL에서 authorization code를 추출
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
const data = {
client_id: 'id-',
client_secret: '비밀번호',
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:3000/oauth/redirect',
scope: 'identify, email',
}
const response = await fetch('https://discord.com/api/oauth2/token', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const responseData = await response.json();
console.log(responseData.access_token); // Here is your access token
}
};
// 임시 스타일 정의
const buttonStyle = {
backgroundColor: 'blue',
color: 'white',
fontSize: '20px',
padding: '10px 20px',
borderRadius: '5px',
border: 'none',
cursor: 'pointer',
};
return (
<button onClick={discordLogin} style={buttonStyle} >
Login with Discord
</button>
);
};
export default DiscordLoginButton;
파일을 생성후 원하는 위치에 import 합니다.
const express = require('express');
const axios = require('axios');
const app = express();
app.listen(3000, () => console.log('Server is listening on port 3000'));
app.get('/', (req, res) => {
res.send('Hello, this is homepage!');
});
app.get('/oauth/redirect', async (req, res) => {
const requestToken = req.query.code;
let tokenResponse, userResponse;
try {
tokenResponse = await axios({
method: 'post',
url: `https://discord.com/api/oauth2/token`,
data: {
client_id: '아이디',
client_secret: '시크릿 키',
grant_type: 'authorization_code',
code: requestToken,
redirect_uri: 'http://localhost:3000/oauth/redirect',
scope: 'identify, email',
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const accessToken = tokenResponse.data.access_token;
// Use the access token to fetch the user's data from Discord API
userResponse = await axios.get('https://discordapp.com/api/users/@me', {
headers: {
authorization: `Bearer ${accessToken}`,
},
});
} catch (error) {
console.error(`Error in getting token or user data from Discord API: ${error.message}`);
return res.status(500).send('Server Error');
}
console.log(userResponse.data); // This logs the user's data
// Then redirect the user back to your react app
res.redirect('http://localhost:3000');
});
express와 axios를 설치후 server.js파일을 만들어 코드를 입력한뒤
node server.js(이때 파일이 있는 위치에서 터미널로 실행합니다.)