반응형
기본 흐름 요약
클라이언트 → Authorization: Bearer <JWT>
↓
JwtBearer 미들웨어
↓
토큰 유효성 검사 (서명, 만료, Issuer, Audience 등)
↓
성공 시 ClaimsPrincipal 생성 → HttpContext.User 에 주입
클라이언트 JWT 생성 예제 코드
public string GenerateJwtToken(string userId)
{
var claims = new[]
{
new Claim("sub", userId)
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super-secret-key-here"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
issuer: "jet.io",
audience: "jet-client",
claims: claims,
expires: DateTime.UtcNow.AddMinutes(60),
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
HTTPS 통신을 위한 자체 인증 SSL 인증서 만들기
전반적인 과정OpenSSL 다운로드Private Key 생성인증서 요청(CSR) 파일 생성(private.csr)자체 서명하기 위해서 rootCA 생성자체 서명한 인증서 생성(private.crt)pem 확장자로 변환NGINX config 파일에서 해당 파일
jettstream.tistory.com
(*secret key를 생성하기 위한 OpenSSL 설치는 해당 링크에서 확인하자.)
openssl rand -hex 64
클라이언트 HTTP 요청 시 토큰에 JWT를 포함
발급받은 토큰을 이제 HTTP 요청과 함께 서버로 보내면 된다.
GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGciOi...
C# HttpClient.PostAsync 사용하기
HttpClient란 무엇인가?HttpClient은 HTTP 요청을 처리하기 위해서 설계된 .NET 라이브러리 내에 존재하는 클래스이다.HttpClient의 장점비동기 실행(Asynchronous Operations) : 응답을 기다리는 동안 다른 처리가
jettstream.tistory.com
(*C#으로 빠르고 쉽게 HTTP 요청 보내는 방법에 대해서는 해당 링크를 확인하자.)
Nuget 패키지 확인
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Program.cs (또는 Startup.cs) 토큰 검증 예제 코드
builder.Services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidTypes ["JWT"],
ValidAlgorithms = ["HS256"],
ValidIssuer = "jet.io",
ValidAudience = "jet-client",
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("super-secret-key-here")),
};
});
인증이 필요한 Contorller내 함수
[Authorize]
[HttpGet("me")]
public IActionResult GetProfile()
{
var userId = _httpContextAccessor.HttpContext?.User.Claims.First(c => c.Type == "sub").Value;
return Ok(new { UserId = userId });
}
함께 읽으면 좋은 글
토큰으로 검증하자! JWT(JSON 웹 토큰)
JWT(JSON Web Token)란?JWT(JSON Web Token)는 사용자 인증 정보를 JSON 형식의 토큰으로 표현하고, 이를 디지털 서명을 통해 안전하게 전달하는 방식이다."서버가 인증을 거친 사용자에게 발급해 주는, 변조
jettstream.tistory.com
'프로그래밍 > C#' 카테고리의 다른 글
Entity Framework에서 [NotMapped] 속성 (0) | 2025.04.26 |
---|---|
C# is 패턴 매칭(Pattern Matching)에 대해서 알아보자 (0) | 2025.04.26 |
ASP.NET Core HTTP 요청 처리 흐름 알아보기 (0) | 2025.04.23 |
C# 환경변수로 appsettings.json 값 덮어쓰기 (0) | 2025.04.12 |
C# 2개의 list 하나로 합치기 (0) | 2025.03.30 |
댓글