iamtokenvalidatorpoc

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 8, 2024 License: Apache-2.0 Imports: 4 Imported by: 0

README

Iam Token Validator

Overview

iamtokenvalidator is a Go package designed to validate and decode JWT tokens using JSON Web Keys (JWK) fetched from a specified MC-IAM-MANAGER endpoint. It provides functionality to verify tokens and extract claims, supporting the RS256, RS384, and RS512 signing methods.

Installation

To install the package, use the following command:

go get github.com/m-cmp/mc-iam-manager/iamtokenvalidator

Usage

Importing the Package

To use iamtokenvalidator in your Go project, import it as follows:

import "github.com/m-cmp/mc-iam-manager/iamtokenvalidator"
Functions
GetPubkeyIamManager

Fetches the JWK set from the provided MC-IAM-MANAGER URL and prepares the public key for token validation.

func GetPubkeyIamManager(host string) error

Parameters:

  • host: The base URL of the MC-IAM-MANAGER service.

Returns:

  • error: An error if fetching the JWK set fails.

Example:

err := iamtokenvalidator.GetPubkeyIamManager("https://your-iam-manager-host")
if err != nil {
    log.Fatalf("Failed to get public key: %v", err)
}
IsTokenValid

Validates the given JWT token string using the previously fetched JWK set.

func IsTokenValid(tokenString string) error

Parameters:

  • tokenString: The JWT token string to validate.

Returns:

  • error: An error if the token is invalid.

Example:

err := iamtokenvalidator.IsTokenValid("your-jwt-token")
if err != nil {
    fmt.Printf("Token is invalid: %v", err)
} else {
    fmt.Println("Token is valid")
}
GetTokenClaimsByIamManagerClaims

Parses the given JWT token string and extracts claims defined in IamManagerClaims.

func GetTokenClaimsByIamManagerClaims(tokenString string) (*IamManagerClaims, error)

Parameters:

  • tokenString: The JWT token string to parse.

Returns:

  • *IamManagerClaims: The extracted claims.
  • error: An error if the token is invalid.

Example:

claims, err := iamtokenvalidator.GetTokenClaimsByIamManagerClaims("your-jwt-token")
if err != nil {
    fmt.Printf("Failed to get claims: %v", err)
} else {
    fmt.Printf("UserID: %s, UserName: %s", claims.UserId, claims.UserName)
}
GetTokenClaimsByCustomClaims

Parses the given JWT token string and extracts custom claims defined by the user.

func GetTokenClaimsByCustomClaims(tokenString string, myclaims interface{}) (interface{}, error)

Parameters:

  • tokenString: The JWT token string to parse.
  • myclaims: A custom claims struct to extract.

Returns:

  • interface{}: The extracted custom claims.
  • error: An error if the token is invalid.

Example:

type CustomClaims struct {
    jwt.StandardClaims
    Email string `json:"email"`
}

var customClaims CustomClaims
claims, err := iamtokenvalidator.GetTokenClaimsByCustomClaims("your-jwt-token", &customClaims)
if err != nil {
    fmt.Printf("Failed to get custom claims: %v", err)
} else {
    fmt.Printf("Email: %s", claims.(*CustomClaims).Email)
}
Supporting Functions
keyfunction

A helper function to support the RS256, RS384, and RS512 signing methods.

func keyfunction(token *jwt.Token) (interface{}, error)

Buffalo Middleware Example

A helper function to support the RS256, RS384, and RS512 signing methods.

func init() {
	r = render.New(render.Options{
		DefaultContentType: "application/json",
	})

	KEYCLOAKHOST := os.Getenv("KEYCLOAK_HOST")
	KEYCLAOKREALM := os.Getenv("KEYCLAOK_REALM")
	fmt.Println("Trying to fetch Pubkey URL :", KEYCLOAKHOST)
	err := iamtokenvalidator.GetPubkeyIamManager(KEYCLOAKHOST + "/realms/" + KEYCLAOKREALM + "/protocol/openid-connect/certs")
	if err != nil {
		panic(err)
	}
}

License

This project is licensed under the Apache License. See the LICENSE file for details.

Contributing

Please feel free to submit issues, fork the repository, and send pull requests!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetPubkeyIamManager

func GetPubkeyIamManager(certUrl string) error

GetPubkeyIamManager는 제공된 MC-IAM-MANAGER url을 통해 "/api/auth/certs" 의 인증서를 받아 공용키를 준비합니다. 정상시 error 를 반환하지 않습니다. jwkSet fetch 오류 발생시 에러를 반환합니다. (panic, fatal 권장)

func GetTokenClaimsByCustomClaims

func GetTokenClaimsByCustomClaims(tokenString string, myclaims interface{}) (interface{}, error)

GetTokenClaimsByCustomClaims는 GetPubkeyIamManager에서 설정된 jwkSet을 바탕으로 tokenString 값을 임의로 정의한 Claims를 사용하여 ParseWithClaims하여 valid 를 검증하고 Claims를 반환합니다. token이 valid 하지 않을시, token is invalid 와 함께 오류 내용을 반환합니다.

func IsTokenValid

func IsTokenValid(tokenString string) error

IsTokenValid는 GetPubkeyIamManager에서 설정된 jwkSet을 바탕으로 tokenString 값을 ParseWithClaims하여 token.Valid를 검증하고 마칩니다. 검증이 성공했을때, error를 반환하지 않습니다. valid 하지 않을시, token is invalid 와 함께 오류 내용을 반환합니다.

func Keyfunction added in v0.1.2

func Keyfunction(token *jwt.Token) (interface{}, error)

Keyfunction은 토큰 검증을 위한 rawkey 를 반환합니다. 미들웨어에서 사용합니다 RS256, RS384, RS512 can be Signing Method

Types

type DefaultClaims

type DefaultClaims struct {
	*jwt.StandardClaims
}

type IamManagerClaims

type IamManagerClaims struct {
	*jwt.StandardClaims
	UserId            string `json:"upn"`
	UserName          string `json:"name"`
	PreferredUsername string `json:"preferred_username"`
	RealmAccess       struct {
		Roles []string `json:"roles"`
	} `json:"realm_access"`
}

func GetTokenClaimsByIamManagerClaims

func GetTokenClaimsByIamManagerClaims(tokenString string) (*IamManagerClaims, error)

GetTokenInfoByIamManagerClaim는 GetPubkeyIamManager에서 설정된 jwkSet을 바탕으로 tokenString 값을 IamManagerClaims에 정의된 UserId, UserName, PreferredUsername, RealmAccess 및 jwt.StandardClaims 를 사용하여 ParseWithClaims하여 valid 를 검증하고 IamManagerClaims를 반환합니다. token이 valid 하지 않을시, token is invalid 와 함께 오류 내용을 반환합니다.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL