백엔드 개발에서 인증 서버는 매우 중요한 역할을 합니다. 사용자의 신원을 확인하고, 안전하게 데이터를 보호하는 기능을 제공합니다. 이번 글에서는 Go 언어를 사용하여 간단한 인증 서버를 구축하는 방법을 알아보겠습니다. 이 서버는 JWT(JSON Web Token)를 활용하여 사용자 인증을 처리합니다.
사전 준비
Go 언어가 설치되어 있어야 하며, HTTP 요청을 처리하기 위해 net/http 패키지를 사용합니다. 또한 JWT 생성을 위해 github.com/dgrijalva/jwt-go 라이브러리를 사용할 것입니다. 이 패키지는 JWT 토큰 생성 및 검증을 손쉽게 도와줍니다.
go get -u github.com/dgrijalva/jwt-go
기본 구조 설정
먼저 Go 프로젝트의 기본 구조를 설정합니다. 아래와 같이 main.go 파일을 생성합니다.
package main
import (
"fmt"
"net/http"
"encoding/json"
"time"
"github.com/dgrijalva/jwt-go"
)
var mySigningKey = []byte("secret")
type Credentials struct {
Username string json:"username"
Password string json:"password"
}
type Claims struct {
Username string json:"username"
jwt.StandardClaims
}
위 코드에서는 기본적인 패키지를 임포트하고, JWT의 서명 키, 사용자 인증을 위한 Credential 구조체, JWT의 Claims 구조체를 정의합니다.
로그인 엔드포인트 구현
로그인 엔드포인트를 구현하여 사용자의 자격 증명을 확인하고, 인증에 성공하면 JWT 토큰을 발급합니다.
func login(w http.ResponseWriter, r http.Request) {
var creds Credentials
if err := json.NewDecoder(r.Body).Decode(&creds); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if creds.Username != "user" || creds.Password != "pass" {
http.Error(w, "Invalid credentials", http.StatusUnauthorized)
return
}
expirationTime := time.Now().Add(5 time.Minute)
claims := &Claims{
Username: creds.Username,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(mySigningKey)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Expires: expirationTime,
})
w.Write([]byte(tokenString))
}
위 코드는 사용자가 user와 pass라는 자격 증명을 입력했는지 확인하는 간단한 로그인 로직입니다. 자격 증명이 유효하면 JWT 토큰을 생성하고, 이를 응답으로 클라이언트에 반환합니다.
인증 미들웨어 구현
이제 인증이 필요한 엔드포인트를 보호하기 위한 미들웨어를 구현합니다. 이 미들웨어는 요청에 포함된 JWT를 검증합니다.
func isAuthenticated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r http.Request) {
cookie, err := r.Cookie("token")
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
tokenStr := cookie.Value
claims := &Claims{}
token, err := jwt.ParseWithClaims(tokenStr, claims, func(token jwt.Token) (interface{}, error) {
return mySigningKey, nil
})
if err != nil || !token.Valid {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
이 미들웨어는 요청의 쿠키에서 JWT를 가져와서 검증합니다. 유효하지 않을 경우에는 "Unauthorized" 에러를 반환합니다.
보호된 엔드포인트 추가
이제 인증이 필요한 보호된 엔드포인트를 추가해보겠습니다.
func welcome(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Welcome! You are authenticated."))
}
이제 이 엔드포인트는 인증 미들웨어를 통해 보호됩니다. 메인 함수에서 모든 라우팅을 설정합니다.
func main() {
http.HandleFunc("/login", login)
http.Handle("/welcome", isAuthenticated(http.HandlerFunc(welcome)))
fmt.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
마무리
이제 간단한 인증 서버가 완성되었습니다. 사용자는 /login 엔드포인트에 POST 요청을 보내어 로그인하고, 로그인 성공 시 JWT 토큰을 받습니다. 이 토큰을 사용하여 보호된 /welcome 엔드포인트에 접근할 수 있습니다.
이 코드는 간단한 구조를 보여줄 뿐만 아니라, JWT를 활용한 인증의 기본적인 흐름을 이해하는 데 도움을 줄 것입니다. 실제 서비스에서는 더 많은 보안 및 사용자 관리 로직이 필요하지만, 이 예제를 통해 Go 언어로 인증 서버를 구축하는 기초를 익힐 수 있습니다.