Skip to content

Instantly share code, notes, and snippets.

@wickedev
Created November 28, 2016 05:55
Show Gist options
  • Save wickedev/3c790d68fc5e81d0df4d1908b13d8817 to your computer and use it in GitHub Desktop.
Save wickedev/3c790d68fc5e81d0df4d1908b13d8817 to your computer and use it in GitHub Desktop.
package auth
import (
"crypto/rsa"
"eng-server/api/utils"
jwt "github.com/dgrijalva/jwt-go"
"github.com/kataras/iris"
"reflect"
"strings"
"time"
)
type JWTAuthenticationBackend struct {
privateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
}
var authBackendInstance *JWTAuthenticationBackend = nil
const JWTExpirationDelta = 72
// JWT Singleton Instance
func InitJWTAuthenticationBackend() *JWTAuthenticationBackend {
if authBackendInstance == nil {
authBackendInstance = &JWTAuthenticationBackend{
privateKey: getPrivateKey(),
PublicKey: getPublicKey(),
}
}
return authBackendInstance
}
// 토큰 생성
func (backend *JWTAuthenticationBackend) GenerateToken(userUUID string) ([]byte, error) {
token := jwt.NewWithClaims(jwt.SigningMethodRS512, jwt.MapClaims{
"exp": time.Now().Add(time.Hour * time.Duration(JWTExpirationDelta)).Unix(),
"iat": time.Now().Unix(),
"sub": userUUID,
})
tokenString, err := token.SignedString(backend.privateKey)
if err != nil {
return nil, err
}
return []byte(tokenString), nil
}
// JWT token 검증 미들웨어
type JwtMiddleware struct{}
// JWT token 검증 미들웨어 핸들러
func (m *JwtMiddleware) Serve(c *iris.Context) {
authBackend := InitJWTAuthenticationBackend()
tokenStr := getToken(string(c.Request.Header.Peek("Authorization")))
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
return authBackend.PublicKey, nil
})
if err != nil {
utils.NoError(c, err)
} else {
c.Set("token", token)
c.Next()
}
}
// Authorization 필드에서 Bearer 를 제거하고 token 스트링만 추출
func getToken(h string) string {
tokenParts := strings.Split(h, " ")
if len(tokenParts) != 2 || tokenParts[0] != "Bearer" || tokenParts[1] == "" {
return ""
}
return tokenParts[1]
}
// token interface{}를 reflection 하여 *jwt.Token 으로 복원
func tokenReflect(tokenIntf interface{}) *jwt.Token {
return reflect.ValueOf(tokenIntf).Interface().(*jwt.Token)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment