JWT(JSON Web Token) PHP 로그인 구현

2024. 11. 16. 09:20·Web/개발

JWT(JSON Web Token)란?

JWT_class.php

<?php
class JWT {
    private $secretKey;

    public function __construct() {
        $this->secretKey = "SSSCCCPPPAAANNNDDDYYYOOO";
    }

    private function base64UrlEncode($data) {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
    }

    public function hashing($payload) {
        $header = [
            'alg' => 'HS256',
            'typ' => 'JWT'
        ];

        $header = $this->base64UrlEncode(json_encode($header));
        $payload = $this->base64UrlEncode(json_encode($payload));

        $signature = hash_hmac('sha256', $header . "." . $payload, $this->secretKey, true);
        $signature = $this->base64UrlEncode($signature);

        return $header . "." . $payload . "." . $signature;
    }

    public function dehashing($token) {
        list($header, $payload, $signature) = explode('.', $token);
        $new_signature = hash_hmac('sha256', "$header.$payload", $this->secretKey, true);
        $new_signature = $this->base64UrlEncode($new_signature);
        if ($signature===$new_signature){
            return true;
        }
        else{
            echo "<script>alert('서명 검증 실패');</script>";
            return false;
        }
    }
}

login.php

<?php
$conn=mysqli_connect("localhost","keshu","1234","JWT");
require 'JWT_class.php';

$jwt = new JWT();

$name = $_POST['name'];
$pw = $_POST['pw'];
$sql="SELECT * FROM test where name='$name' and pw='$pw'";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_object($result);

    if ($row) {
        $payload = [
            'name' => $name,
        ];

        $token = $jwt->hashing($payload);

        setcookie("token", $token, time()+86400, "/", "", false, true);

        echo "<script>alert('로그인 성공');";
        echo "location='profile.php';</script>";
    }

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link href="/login.css" rel="stylesheet" type="text/css">
    <title>Login</title>
    <h1>로그인 페이지</h1>
</head>
<body>
    <table align="center" class="list">
        <form method="post" action="login.php">
            <tr><td><input class="member" type="text" name="name" placeholder="ID" required></td></tr>
            <tr><td><input class="member" type="text" name="pw" placeholder="Password" required></td></tr>
            <tr><td align="center"><input type="submit" value="로그인" class="button">
        </form>
    </table>
</body>
</html>

profile.php

<link href="/profile.css" rel="stylesheet" type="text/css">
<?php
$conn=mysqli_connect("localhost","keshu","1234","JWT");
$sql="select * from test";
$result=mysqli_query($conn,$sql);
$num=mysqli_num_rows($result);
require 'JWT_class.php';

$jwt = new JWT();

if (!isset($_COOKIE['token'])) {
    echo "<script>alert('로그인 후 이용 가능');";
    echo "location='/login.php';</script>";
    exit;
}

$token = $_COOKIE['token'];

if ($jwt->dehashing($token)) {
    list($header, $payload, $signature) = explode('.', $token);
    $payload = json_decode(base64_decode($payload),true);
    if (($payload['name'])=='admin'){
?>
    <h1>관리자 정보 및 회원 정보</h1>
    <h3>name: admin</h3>
        <div>
        <table class="list" align="center" border="1">
        <thead>
            <tr>
            <th>username</th>
            <th>password</th>
            </tr>
        </thead>
        <?php
            for($i=1;$i<=$num;$i++){
            $row=mysqli_fetch_object($result);
        ?>
        <tbody>
        <tr> 
            <td style="width: 10%;"><?=$row->name?></td>
            <td style="width: 10%;"><?=$row->pw?></td>
        </tr>
        <?php
            }mysqli_close($conn);
    } else{
?>
        <h1>사용자 정보</h1>
        <h3>name: <?= $payload['name']; ?></h3>
        <div class='logout'><a href='/login.php'><button>로그아웃</button></a></div>
<?php    
    }
}
?>

logout.php

<?php
setcookie("token", "", time()-86400, "/");
echo "location='/login.php'";
?>

'Web > 개발' 카테고리의 다른 글

JWT(JSON Web Token)란?  (1) 2024.11.15
Web Token이란?  (1) 2024.11.15
Web Template Engine이란?  (0) 2024.10.24
API란?  (0) 2024.09.19
'Web/개발' 카테고리의 다른 글
  • JWT(JSON Web Token)란?
  • Web Token이란?
  • Web Template Engine이란?
  • API란?
Pandyo
Pandyo
판됴의 성장 스토리 'ㅅ'
  • Pandyo
    dyostory
    Pandyo
  • 전체
    오늘
    어제
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • Kategorie (36)
      • Web (1)
        • Web Hacking (10)
        • 언어 (2)
        • 개발 (5)
        • DataBase (2)
      • Cloud (1)
        • CloudGoat (1)
        • 실습 (0)
      • Project (11)
        • Cloud (11)
      • Wargame (4)
        • Dreamhack (1)
        • CTF (1)
        • Wargame site (2)
  • 링크

  • 태그

    Cloud
    Blue/Green
    Injection
    NoSQL
    AWS
    jws
    Route Table
    Fargate
    JWT
    Internet GateWay
    target group
    Token
    XML
    graphql
    Web
    WebHacking
    Rolling Update
    vulnerability
    buildspec.yml
    canary release
    devops
    ecs
    배포 방식
    무중단배포
    CI/CD
    API
    template
    cloudgoat
    DBMS
    file
  • hELLO· Designed By정상우.v4.10.0
Pandyo
JWT(JSON Web Token) PHP 로그인 구현
상단으로

티스토리툴바