Kaikas로그인 정보를 백엔드로 넘기는 방법이 있나요?

안녕하세요

Caver를 이용해 클라이언트에서 SignedMessage 를 만들고 서버에서 보내 서버에서 검증하시면 됩니다.

아래 간단한 예제 추가했습니다.


Client

import Caver from 'caver-js';

async function bootstrap() {
  const caver = new Caver((window as any).klaytn);
  const [address] = await (window as any).klaytn.enable();
  const signedMessage = await caver.rpc.klay.sign(address, 'my message');

  const payload = await fetch('http://localhost:3001/verify', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      address,
      signedMessage,
    }),
  });

  console.log(await payload.json());

}

bootstrap();

Server

import Caver from 'caver-js';
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';

const caver = new Caver('https://public-node-api.klaytnapi.com/v1/baobab');

async function validateSignedMessage(message: string, signedMessage: string, address: string) {
  const v = '0x' + signedMessage.substring(2).substring(128, 130);
  const r = '0x' + signedMessage.substring(2).substring(0, 64);
  const s = '0x' + signedMessage.substring(2).substring(64, 128);
  return await caver.validator.validateSignedMessage(
    message,
    [v, r, s],
    address,
    false,
  );
}

const app = express();

app.use(cors());
app.use(bodyParser());

app.post('/verify', async (req, res) => {
  const { address, signedMessage } = req.body;

  const isValid = await validateSignedMessage('my message', signedMessage, address);

  res.json({
    isValid,
  });
});

app.listen(3001, () => {
  console.log('Example app listening on port 3001');
});
2개의 좋아요