Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "time"
- "github.com/golang-jwt/jwt/v5"
- )
- var ErrInvalidToken = errors.New("Invalid token")
- var ErrUnexpectedSigningMethod = errors.New("Unexpected signing method")
- var JwtSecret = []byte("secret")
- var jwtExpirationTime = time.Hour * 72
- func generateToken(username string) (string, error) {
- token := jwt.New(jwt.SigningMethodHS256)
- claims := token.Claims.(jwt.MapClaims)
- claims["username"] = username
- claims["exp"] = time.Now().Add(jwtExpirationTime).Unix()
- tokenString, err := token.SignedString(JwtSecret)
- if err != nil {
- return "", err
- }
- return tokenString, nil
- }
- func validateToken(jwtToken string) (claims jwt.MapClaims, err error) {
- parser := jwt.NewParser(jwt.WithValidMethods([]string{"HS256"}))
- token, err := parser.Parse(jwtToken, func(token *jwt.Token) (interface{}, error) {
- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
- return nil, ErrUnexpectedSigningMethod
- }
- return JwtSecret, nil
- })
- if err != nil {
- return nil, err
- }
- if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
- return claims, nil
- } else {
- return nil, ErrInvalidToken
- }
- }
- func main() {
- http.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
- if r.Method != "POST" {
- w.WriteHeader(http.StatusMethodNotAllowed)
- return
- }
- var loginDto struct {
- Username string `json:"username"`
- }
- err := json.NewDecoder(r.Body).Decode(&loginDto)
- if err != nil {
- w.WriteHeader(http.StatusBadRequest)
- return
- }
- tokenString, err := generateToken(loginDto.Username)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- response, err := json.Marshal(map[string]string{
- "token": tokenString,
- })
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- w.WriteHeader(http.StatusOK)
- w.Write(response)
- w.Write([]byte("\n"))
- })
- http.HandleFunc("/verify", func(w http.ResponseWriter, r *http.Request) {
- fmt.Println("Request Recived")
- headerVal := r.Header.Get("Authorization")
- fmt.Println(headerVal);
- if headerVal == "" || headerVal[:7] != "Bearer " {
- w.WriteHeader(http.StatusUnauthorized)
- return
- }
- tokenString := headerVal[7:]
- claims, err := validateToken(tokenString)
- if err != nil {
- w.WriteHeader(http.StatusUnauthorized)
- return
- }
- response, err := json.Marshal(claims)
- if err != nil {
- w.WriteHeader(http.StatusInternalServerError)
- return
- }
- fmt.Println("Valid");
- w.WriteHeader(http.StatusOK)
- w.Write(response)
- w.Write([]byte("\n"))
- })
- fmt.Println("Auth Service started at port 8080")
- http.ListenAndServe(":8080", nil)
- time.Sleep(time.Second * 1000)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement