Advertisement
Guest User

Untitled

a guest
Sep 17th, 2023
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "time"
  9.  
  10. "github.com/golang-jwt/jwt/v5"
  11. )
  12.  
  13. var ErrInvalidToken = errors.New("Invalid token")
  14. var ErrUnexpectedSigningMethod = errors.New("Unexpected signing method")
  15.  
  16. var JwtSecret = []byte("secret")
  17. var jwtExpirationTime = time.Hour * 72
  18.  
  19. func generateToken(username string) (string, error) {
  20. token := jwt.New(jwt.SigningMethodHS256)
  21.  
  22. claims := token.Claims.(jwt.MapClaims)
  23.  
  24. claims["username"] = username
  25. claims["exp"] = time.Now().Add(jwtExpirationTime).Unix()
  26.  
  27. tokenString, err := token.SignedString(JwtSecret)
  28. if err != nil {
  29. return "", err
  30. }
  31. return tokenString, nil
  32. }
  33.  
  34. func validateToken(jwtToken string) (claims jwt.MapClaims, err error) {
  35. parser := jwt.NewParser(jwt.WithValidMethods([]string{"HS256"}))
  36. token, err := parser.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
  37. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  38. return nil, ErrUnexpectedSigningMethod
  39. }
  40. return JwtSecret, nil
  41. })
  42. if err != nil {
  43. return nil, err
  44. }
  45.  
  46. if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
  47. return claims, nil
  48. } else {
  49. return nil, ErrInvalidToken
  50. }
  51.  
  52. }
  53.  
  54. func main() {
  55.  
  56. http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
  57. if r.Method != "POST" {
  58. w.WriteHeader(http.StatusMethodNotAllowed)
  59. return
  60. }
  61.  
  62. var loginDto struct {
  63. Username string `json:"username"`
  64. }
  65. err := json.NewDecoder(r.Body).Decode(&loginDto)
  66. if err != nil {
  67. w.WriteHeader(http.StatusBadRequest)
  68. return
  69. }
  70.  
  71. tokenString, err := generateToken(loginDto.Username)
  72.  
  73. if err != nil {
  74. w.WriteHeader(http.StatusInternalServerError)
  75. return
  76. }
  77.  
  78. response, err := json.Marshal(map[string]string{
  79. "token": tokenString,
  80. })
  81.  
  82. if err != nil {
  83. w.WriteHeader(http.StatusInternalServerError)
  84. return
  85. }
  86.  
  87. w.WriteHeader(http.StatusOK)
  88. w.Write(response)
  89. w.Write([]byte("\n"))
  90.  
  91. })
  92.  
  93. http.HandleFunc("/verify", func(w http.ResponseWriter, r *http.Request) {
  94. fmt.Println("Request Recived")
  95. headerVal := r.Header.Get("Authorization")
  96. fmt.Println(headerVal);
  97. if headerVal == "" || headerVal[:7] != "Bearer " {
  98. w.WriteHeader(http.StatusUnauthorized)
  99. return
  100. }
  101.  
  102. tokenString := headerVal[7:]
  103.  
  104. claims, err := validateToken(tokenString)
  105. if err != nil {
  106. w.WriteHeader(http.StatusUnauthorized)
  107. return
  108. }
  109.  
  110. response, err := json.Marshal(claims)
  111. if err != nil {
  112. w.WriteHeader(http.StatusInternalServerError)
  113. return
  114. }
  115. fmt.Println("Valid");
  116. w.WriteHeader(http.StatusOK)
  117. w.Write(response)
  118. w.Write([]byte("\n"))
  119.  
  120. })
  121.  
  122. fmt.Println("Auth Service started at port 8080")
  123. http.ListenAndServe(":8080", nil)
  124.  
  125. time.Sleep(time.Second * 1000)
  126.  
  127. }
  128.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement