Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.87 KB | None | 0 0
  1. package jwtmodule
  2.  
  3. import (
  4. "crypto/rsa"
  5. "fmt"
  6. jwt "github.com/dgrijalva/jwt-go"
  7. "io/ioutil"
  8. "log"
  9. )
  10.  
  11. const (
  12. private_path = "/home/jamesbondu/Desktop/developer-hub/Gogo/src/github.com/arujit/jwt/keys/private_key.pem"
  13. public_path = "/home/jamesbondu/Desktop/developer-hub/Gogo/src/github.com/arujit/jwt/keys/public_key.pem"
  14. )
  15.  
  16. type Keys struct {
  17. public *rsa.PublicKey
  18. private *rsa.PrivateKey
  19. }
  20.  
  21. var JWTMngr *Keys
  22.  
  23. func Initialize(public_path, private_path string) error {
  24. var err error
  25. var public, private []byte
  26. var public_key *rsa.PublicKey
  27. var private_key *rsa.PrivateKey
  28. private, err = ioutil.ReadFile(private_path)
  29. if err != nil {
  30. log.Fatal("Error reading private key")
  31. return err
  32. }
  33.  
  34. private_key, _ = jwt.ParseRSAPrivateKeyFromPEM(private)
  35. public, err = ioutil.ReadFile(public_path)
  36.  
  37. if err != nil {
  38. log.Fatal("Error reading public key")
  39. return err
  40. }
  41.  
  42. public_key, _ = jwt.ParseRSAPublicKeyFromPEM(public)
  43. JWTMngr = &Keys{public: public_key, private: private_key}
  44.  
  45. return err
  46. }
  47.  
  48. func Encode(claims map[string]interface{}) (string, error) {
  49.  
  50. claims_token := jwt.MapClaims(claims)
  51. token := jwt.NewWithClaims(jwt.SigningMethodRS512, claims_token)
  52.  
  53. tokenString, err := token.SignedString(JWTMngr.private)
  54. if err != nil {
  55. log.Fatal("Error in Encoding claim")
  56. }
  57. return tokenString, err
  58.  
  59. }
  60.  
  61. func Decode(tokenString string) (map[string]interface{}, error) {
  62. var final_claims map[string]interface{}
  63. token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  64. if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
  65. return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
  66. }
  67. return JWTMngr.public, nil
  68.  
  69. })
  70.  
  71. claims, _ := token.Claims.(jwt.MapClaims)
  72.  
  73. final_claims = nil
  74. if token.Valid {
  75. err = nil
  76. final_claims = map[string]interface{}(claims)
  77. } else {
  78. err = fmt.Errorf("Not valid token")
  79.  
  80. }
  81. return final_claims, err
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement