Skip to content

Latest commit

 

History

History
134 lines (108 loc) · 3.98 KB

csharp-jwt-token.md

File metadata and controls

134 lines (108 loc) · 3.98 KB

JWT 이해 및 C#을 통한 구현방법

이 리포지토리는 JWT 이해 및 C#을 통한 구현방법에 대해 기술한 리포지토리입니다.

더 알아보기 »

Star License Activity
Github Stars License Commits-per-month

JWT에 대한 전반적인 개념과 기술에 대해 설명합니다. 그리고 C#을 통한 JWT 구현 방법도 제공하고 있습니다.

내용


JSON 웹 토큰 (Json Web Token, JWT)

image
JSON 웹 토큰
(Json Web Token, JWT)
Header, Payload, Signiture

URL-Safe

TBD...


JWT 구조

JWT는 3개의 구조로 이루어져 있는 Base64 형태의 암호화된 인증 체계 값입니다.

Header

{
    "alg": "HS256",
    "typ": "JWT"
}

Payload

{
    "sub": "1234567890",
    "name": "John Doe",
    "admin": true
}

Signiture

HMAC_SHA256(
    secret,
    base64urlEncoding(header) + '.' +
    base64urlEncoding(payload)
)

JWT 생성

다음은 C#에서 JwtToken을 생성하는 방법입니다.

public string GenerateToken(ApplicationUser user)
{
    // generate token that is valid for 7 days
    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(mySecret);
    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };
    var token = tokenHandler.CreateToken(tokenDescriptor);
    return tokenHandler.WriteToken(token);
}

JWT Validation 체크

public string ValidateToken(string token)
{
    if (token == null)
        return null;

    var tokenHandler = new JwtSecurityTokenHandler();
    var key = Encoding.ASCII.GetBytes(mySecret);
    try
    {
        tokenHandler.ValidateToken(token, new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false,
            // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later)
            ClockSkew = TimeSpan.Zero
        }, out SecurityToken validatedToken);

        var jwtToken = (JwtSecurityToken)validatedToken;
        var userId = jwtToken.Claims.First(x => x.Type == "id").Value;

        // return user id from JWT token if validation successful
        return userId;
    }
    catch
    {
        // return null if validation fails
        return null;
    }
}

참고 문헌