WIL : Json Web Token (JWT)

Adam Sung Min Park·2022년 9월 25일
0

It is hard to see any applications that does not have a login function.

Login grants two major concepts to the users:
1. Authentication (checking who this user is)
2. Authorization (what kind of rights does this user have?)

In modern days, it is common to use Json Web Token(JWT) to accomplish login function.

So what is JWT?

JWT token is a token generated by the authentication server and contains the end user's info.

JWT consists of 3 parts, Header, Payload and Signature.

Header consists of two parts: the type of token(JWT) and the signing algorithm being used.

Payload contains the claims which are user information.

Signature is used to verify the message wasn't changed along the way. It verifies the sender of the JWT.

once the user successfully logs in, a JWT will be returned.

Why did we use JWT?

While I was working on my project, my team decided to use JWT. Since the user information is not stored in the server side, it is more reliable and light on the server.

How did we use JWT?

In order to implement the log in function, we first needed to establish a REST API to the server.

# server side
@app.route('/sign_in', methods=['POST'])
def sign_in():
    username_receive = request.form['username_give']
    password_receive = request.form['password_give']
    pw_hash = hashlib.sha256(password_receive.encode('utf-8')).hexdigest()
    result = db.users.find_one({'username': username_receive, 'password': pw_hash})
    if result is not None:
        payload = {
            'id': username_receive,
            'exp': datetime.datetime.utcnow() + timedelta(seconds=60 * 5)  # 로그인 5분 유지
        }
        token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
        return jsonify({'result': 'success', 'token': token})
    # if not found
    else:
        return jsonify({'result': 'fail', 'msg': 'Incorrect ID/Password.'})
# client side
function sign_in() {
            let username = $("#input-username").val()
            let password = $("#input-password").val()

            if (username == "") {
                $("#help-id-login").text("Input your ID.")
                $("#input-username").focus()
                return;
            } else {
                $("#help-id-login").text("")
            }

            if (password == "") {
                $("#help-password-login").text("Type in your password.")
                $("#input-password").focus()
                return;
            } else {
                $("#help-password-login").text("")
            }
            $.ajax({
                type: "POST",
                url: "/sign_in",
                data: {
                    username_give: username,
                    password_give: password
                },
                success: function (response) {
                    console.log(response)
                    if (response['result'] == 'success') {
                        $.cookie('mytoken', response['token'], {path: '/'});
                        window.location.replace("/")
                    } else {
                        alert(response['msg'])
                    }
                }
            });
        }

Once the info have been gathered from the client side, it will send a "POST" method to the designated API /sign_in.
Once the server checks the credential of the user, it will return the JWT.

What have I learned?

Definitely more about how important it is to securely save user information on the server side and why JWT is used widely among the programmers. Will look more into other methods such as OAuth or Bearer's token. I think it will come handy to pick and choose which method to use accordingly to the situation.

0개의 댓글