Ejemplo n.º 1
0
func (a *authService) GenerateToken(user *schema.User) (*TokenFields, error) {

	expiresAt := time.Now().Add(time.Hour * 2)

	token := jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["uid"] = user.ID
	token.Claims["uname"] = user.Username
	token.Claims["iat"] = expiresAt.Unix()

	accessToken, err := token.SignedString(a.SigningKey)
	if err != nil {
		return nil, err
	}

	// generate JWT access token
	token = jwt.New(jwt.GetSigningMethod("HS256"))
	token.Claims["uid"] = user.ID
	token.Claims["uname"] = user.Username
	token.Claims["iat"] = time.Now().Add(time.Hour * 24 * 14).Unix()

	refreshToken, err := token.SignedString(a.RefreshKey)
	if err != nil {
		return nil, err
	}

	return &TokenFields{AccessToken: accessToken, RefreshToken: refreshToken, ExpiresAt: expiresAt}, nil
}
Ejemplo n.º 2
0
func mockLoginTokenWithoutID(expires time.Time, auth_key []byte) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	// Set some claims
	token.Claims["exp"] = expires.Unix()
	// Sign and get the complete encoded token as a string
	return token.SignedString(auth_key)
}
Ejemplo n.º 3
0
func main() {
	r := gin.Default()

	public := r.Group("/api")

	public.GET("/", func(c *gin.Context) {
		// Create the token
		token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
		// Set some claims
		token.Claims["ID"] = "Christopher"
		token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
		// Sign and get the complete encoded token as a string
		tokenString, err := token.SignedString([]byte(mysupersecretpassword))
		if err != nil {
			c.JSON(500, gin.H{"message": "Could not generate token"})
		}
		c.JSON(200, gin.H{"token": tokenString})
	})

	private := r.Group("/api/private")
	private.Use(jwt.Auth(mysupersecretpassword))

	/*
		Set this header in your request to get here.
		Authorization: Bearer `token`
	*/

	private.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello from private"})
	})

	r.Run("localhost:8080")
}
Ejemplo n.º 4
0
func (as *authServer) Login(ctx context.Context, request *pb.LoginRequest) (*pb.LoginResponse, error) {
	user, err := getUser(db, request.Username)
	if err != nil {
		return nil, err
	}
	err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(request.Password))
	if err != nil {
		return nil, grpc.Errorf(codes.PermissionDenied, "")
	}

	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	token.Claims["admin"] = user.IsAdmin
	token.Claims["iss"] = "auth.service"
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["email"] = user.Email
	token.Claims["sub"] = user.Username

	tokenString, err := token.SignedString(as.jwtPrivatekey)
	if err != nil {
		return nil, grpc.Errorf(codes.Internal, err.Error())
	}

	return &pb.LoginResponse{tokenString}, nil
}
Ejemplo n.º 5
0
// generate jwt token and return to client
func JwtGetToken(c *gin.Context) {
	var login Login
	val := c.Bind(&login)
	if !val {
		c.JSON(200, gin.H{"code": 401, "msg": "Both name & password are required"})
		return
	}
	//	if login.Name == validUser.Name && login.Pass == validUser.Pass {
	token := jwt.New(jwt.SigningMethodHS256)
	// Headers
	token.Header["alg"] = "HS256"
	token.Header["typ"] = "JWT"

	// Claims
	token.Claims["name"] = validUser.Name
	token.Claims["mail"] = validUser.Mail
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err := token.SignedString([]byte(mySigningKey))

	fmt.Println("jwt token raw: ", tokenString)

	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "Server error!"})
		return
	}
	c.JSON(200, gin.H{"code": 200, "msg": "OK", "jwt": tokenString})
	//	} else {
	//		c.JSON(200, gin.H{"code": 400, "msg": "Error username or password!"})
	//	}
}
Ejemplo n.º 6
0
func login(c echo.Context) error {
	username := c.FormValue("username")
	password := c.FormValue("password")

	if username == "jon" && password == "shhh!" {
		// Create token
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = "Jon Snow"
		claims["admin"] = true
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
	}

	return echo.ErrUnauthorized
}
Ejemplo n.º 7
0
// Create JSON Web Token
func (c *Client) setToken(r *http.Request) error {

	token := jwt.New(jwt.SigningMethodHS256)

	// Set issuer
	token.Claims["iss"] = c.user

	// Set issued at time
	token.Claims["iat"] = time.Now().Unix()

	// Set expiration
	token.Claims["exp"] = time.Now().Add(time.Minute * 5).Unix()

	// Set qsh hash
	qshstring := r.Method + "&" + r.URL.Path
	hash := sha256.New()
	hash.Write([]byte(qshstring))
	token.Claims["qsh"] = hex.EncodeToString(hash.Sum(nil))

	// Sign the token
	signedtoken, err := token.SignedString([]byte(c.key))
	if err != nil {
		return err
	}

	// Save it in the header
	r.Header.Set("Authorization", "bearer "+signedtoken)

	return nil
}
Ejemplo n.º 8
0
// Expects username & password to be passed as JSON in the POST body
// This is how Ember does it.
func (s *APIServer) login(c echo.Context) error {
	a := new(AuthInfo)

	if err := c.Bind(a); err != nil {
		return err
	}

	dbuser, err := s.DBH.GetUserByEmail(a.Username)
	if err == nil {
		//if bcrypt.CompareHashAndPassword([]byte(dbuser.Password), []byte(a.Password)) == nil {
		token := jwt.New(jwt.SigningMethodHS256)

		// Set claims
		claims := token.Claims.(jwt.MapClaims)
		claims["name"] = dbuser.Email
		claims["admin"] = false
		claims["exp"] = time.Now().Add(time.Hour * 72).Unix()

		// Generate encoded token and send it as response.
		t, err := token.SignedString([]byte("secret"))
		if err != nil {
			return err
		}
		return c.JSON(http.StatusOK, map[string]string{
			"token": t,
		})
		//}
	}

	logrus.Infof("Unknown user or bad password for: %s", a.Username)
	return c.String(http.StatusUnauthorized, "Bad username or password")
}
Ejemplo n.º 9
0
func (ja *JwtAuth) Encode(claims Claims) (t *jwt.Token, tokenString string, err error) {
	t = jwt.New(ja.signer)
	t.Claims = claims
	tokenString, err = t.SignedString(ja.signKey)
	t.Raw = tokenString
	return
}
Ejemplo n.º 10
0
func TestJWTToken(t *testing.T) {
	var err error
	if privateKey, err = ioutil.ReadFile("rsa-test.key"); err != nil {
		t.Fatal(err)
	}
	if publicKey, err = ioutil.ReadFile("rsa-test.pub"); err != nil {
		t.Fatal(err)
	}
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["PERMISSION"] = "admin@tiedot"
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	ts, err := token.SignedString(privateKey)
	if err != nil {
		t.Fatal(err)
	}
	if token, err = jwt.Parse(ts, func(ts *jwt.Token) (interface{}, error) {
		return publicKey, nil
	}); err != nil {
		t.Fatal(err)
	}
	if token.Valid {
		t.Log(token)
	} else {
		t.Log(token)
		t.Fail()
	}
}
Ejemplo n.º 11
0
Archivo: auth.go Proyecto: oblank/forum
/**

	TODO:
	- Get email and password from post request
	- Find user

**/
func (a *authController) Login(c *gin.Context) {
	var userLogin models.UserLogin
	if err := c.Bind(&userLogin); err != nil {
		panic(err)
	}
	user, err := authResource.Login(userLogin.Email, userLogin.Password)
	if err != nil {
		c.Error(err)
		return
	}
	token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
	// Set some claims
	token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
	// Sign and get the complete encoded token as a string
	apiKey, err := token.SignedString([]byte(config.GetSecret()))
	if err != nil {
		c.Error(apiErrors.ThrowError(apiErrors.ServerError))
		return
	}
	// Remove password
	user.Password = ""

	c.JSON(200, gin.H{
		"user":    user,
		"api-key": apiKey,
	})
}
Ejemplo n.º 12
0
Archivo: auth.go Proyecto: grffn/movier
//LoginHandler Hndler for login method
func LoginHandler(context *gin.Context, database *db.Context) {
	var model models.LoginModel
	err := context.BindJSON(&model)
	if err != nil {
		log.Println(err)
		context.AbortWithError(http.StatusBadRequest, err)
		return
	}
	user := database.FindUser(model.UserID)
	storedPassword, _ := base64.URLEncoding.DecodeString(user.Password)
	salt, _ := base64.URLEncoding.DecodeString(user.Salt)
	checkPassword, _ := util.GeneratePassword([]byte(model.Password), salt)
	if bytes.Compare(storedPassword, checkPassword) == 0 {
		token := jwt_lib.New(jwt_lib.GetSigningMethod("HS256"))
		token.Claims["ID"] = user.Username
		token.Claims["exp"] = time.Now().Add(time.Hour * 24).Unix()
		tokenString, err := token.SignedString([]byte(secret))
		if err != nil {
			context.JSON(500, gin.H{"message": "Could not generate token"})
			return
		}
		context.JSON(200, gin.H{"token": tokenString})
	} else {
		context.JSON(http.StatusUnauthorized, gin.H{"status": "Login or password is incorrect"})
	}
}
Ejemplo n.º 13
0
// http://openid.net/specs/openid-connect-core-1_0.html#IDToken
func (s *Server) generateIDToken(userData interface{}, client Client, scopesString string, nonce string, accessToken string) (string, error) {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims["iss"] = s.Config.Issuer
	token.Claims["sub"] = userData.(User).GetSub()
	token.Claims["aud"] = client.GetId()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["nonce"] = nonce
	token.Claims["exp"] = time.Now().Add(time.Duration(s.Config.IDTokenExpiration) * time.Second).Unix()
	if accessToken != "" {
		hasher := sha256.New()
		io.WriteString(hasher, accessToken)
		sum := hasher.Sum(nil)
		accessTokenHash := base64.URLEncoding.EncodeToString(sum[0 : len(sum)/2])
		token.Claims["at_hash"] = accessTokenHash
	}
	scopes := strings.Split(scopesString, " ")
	for _, scope := range scopes {
		claims := s.ClaimManager.GetClaims(scope, userData)
		for k, v := range claims {
			token.Claims[k] = v
		}
	}
	// kid
	token.Header["kid"] = s.Config.JWTKeyID
	key, _ := jwt.ParseRSAPrivateKeyFromPEM(s.Config.JWTKey)
	a, err := token.SignedString(key)
	return a, err
}
Ejemplo n.º 14
0
// WithIdentity fills the context with token
// Token is filled using input Identity object
func WithIdentity(ctx context.Context, ident account.Identity) context.Context {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims.(jwt.MapClaims)["sub"] = ident.ID.String()
	token.Claims.(jwt.MapClaims)["uuid"] = ident.ID.String()
	token.Claims.(jwt.MapClaims)["fullName"] = ident.User.FullName
	token.Claims.(jwt.MapClaims)["imageURL"] = ident.User.ImageURL
	return goajwt.WithJWT(ctx, token)
}
Ejemplo n.º 15
0
// create a jwt token
func createJWTToken(serviceId string, backOffice bool, expires_in int64) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["service_id"] = serviceId
	token.Claims["expires_in"] = expires_in
	token.Claims["back_office"] = backOffice
	tokenString, err := token.SignedString([]byte(SigningKey))
	return tokenString, err
}
Ejemplo n.º 16
0
// GenerateToken - generate Token string
func GenerateToken() string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
	tokenString, err := token.SignedString(signKey)
	fatal(err)

	return tokenString
}
Ejemplo n.º 17
0
// getExpiredAuthHeader returns a valid JWT bearer token
func getValidAuthHeader(t *testing.T, key interface{}) string {
	token := jwt.New(jwt.SigningMethodRS256)
	tokenStr, err := token.SignedString(key)
	if err != nil {
		t.Fatal("Could not sign the token ", err)
	}
	return fmt.Sprintf("Bearer %s", tokenStr)
}
Ejemplo n.º 18
0
// GenerateToken - generates a new Json Web Token based on the incoming user id.
func (jwt *JWT) GenerateToken(userName string) (string, error) {
	token := jwtgo.New(jwtgo.SigningMethodHS512)
	// Token expires in 10hrs.
	token.Claims["exp"] = time.Now().Add(time.Hour * tokenExpires).Unix()
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["sub"] = userName
	return token.SignedString([]byte(jwt.SecretAccessKey))
}
Ejemplo n.º 19
0
// key is the secret key for encoding token
// claims is the infomation you want to store in token, usually, a user's name or more
// for example:
// user := map[string]interface{}{"name": "yourname"}
// token, err := jwt.Sign("yourkey", user)
// In neo, middlewares are runned before any route,
// so you need set Regions, otherwise every route gonna be verified by jwt
// check it here: http://ivpusic.github.io/neo/tutorials/2015/01/22/regions.html
func Sign(key string, claims map[string]interface{}) (string, error) {
	// Create the token
	token := jwt_go.New(jwt_go.SigningMethodHS256)
	// Set claims
	token.Claims = claims
	// Sign and get the complete encoded token as a string
	return token.SignedString([]byte(key))
}
Ejemplo n.º 20
0
func (authen *Authen) getJwtForUser(userid string, username string, duration int, changePassword bool) (string, error) {
	userid = strings.ToLower(userid)
	token := jwt.New(jwt.SigningMethodHS512)
	token.Claims["userid"] = userid
	token.Claims["username"] = username
	token.Claims["cp"] = changePassword
	token.Claims["exp"] = time.Now().Add(time.Second * time.Duration(duration)).Unix()
	return token.SignedString(authen.privateKey)
}
Ejemplo n.º 21
0
func CreateToken(hostUuid string, privateKey interface{}) string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["hostUuid"] = hostUuid
	signed, err := token.SignedString(privateKey)
	if err != nil {
		log.Fatal("Failed to parse private key.", err)
	}
	return signed
}
Ejemplo n.º 22
0
func handleLogin(w http.ResponseWriter, r *http.Request) {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims["ID"] = "This is my super fake ID"
	token.Claims["exp"] = time.Now().Unix() + 30
	tokenString, _ := token.SignedString(privateKey)

	w.WriteHeader(http.StatusOK)
	fmt.Fprintf(w, `{"token": %s}`, tokenString)
}
Ejemplo n.º 23
0
func TestCurrentAuthorizedMissingUUID(t *testing.T) {
	t.Parallel()
	resource.Require(t, resource.UnitTest)
	jwtToken := token.New(token.SigningMethodRS256)
	ctx := jwt.WithJWT(context.Background(), jwtToken)

	controller := newUserController(nil, nil)
	test.ShowUserBadRequest(t, ctx, nil, controller)
}
Ejemplo n.º 24
0
// getExpiredAuthHeader returns a JWT bearer token with an expiration date that lies in the past
func getExpiredAuthHeader(t *testing.T, key interface{}) string {
	token := jwt.New(jwt.SigningMethodRS256)
	token.Claims = jwt.MapClaims{"exp": float64(time.Now().Unix() - 100)}
	tokenStr, err := token.SignedString(key)
	if err != nil {
		t.Fatal("Could not sign the token ", err)
	}
	return fmt.Sprintf("Bearer %s", tokenStr)
}
Ejemplo n.º 25
0
func CreateTokenWithPayload(payload map[string]interface{}, privateKey interface{}) string {
	token := jwt.New(jwt.GetSigningMethod("RS256"))
	token.Claims = payload
	signed, err := token.SignedString(privateKey)
	if err != nil {
		log.Fatal("Failed to parse private key.", err)
	}
	return signed
}
Ejemplo n.º 26
0
// New creates a new jwt token.
func (t Token) New(id string, exp time.Time) (string, error) {
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["sub"] = id
	token.Claims["iss"] = t.ISS
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["exp"] = exp.Unix()
	// Sign and get the complete encoded token as a string
	return token.SignedString([]byte(t.Secret))
}
Ejemplo n.º 27
0
// Login attempts to login the user given a request. Only works for local passwd at this time
func GetLoginFunc(db *sqlx.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		username := ""
		password := ""
		body, err := ioutil.ReadAll(r.Body)
		if err != nil {
			log.Println("Error reading body: ", err.Error())
			http.Error(w, "Error reading body: "+err.Error(), http.StatusBadRequest)
			return
		}
		var lj loginJson
		log.Println(body)
		err = json.Unmarshal(body, &lj)
		if err != nil {
			log.Println("Error unmarshalling JSON: ", err.Error())
			http.Error(w, "Invalid JSON: "+err.Error(), http.StatusBadRequest)
			return
		}
		username = lj.U
		password = lj.P
		u := api.TmUser{}
		u, err = api.GetTmUserByName(username, db)
		if err != nil {
			http.Error(w, "Invalid user: "******"user", nil)
			log.Println("Invalid passwd")
			http.Error(w, "Invalid password: "******"userid"] = u.Id
		token.Claims["role"] = u.Links.RoleLink.ID
		token.Claims["exp"] = time.Now().Add(time.Hour * 72).Unix()
		// Sign and get the complete encoded token as a string
		tokenString, err := token.SignedString([]byte("mySigningKey")) // TODO JvD
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		js, err := json.Marshal(TokenResponse{Token: tokenString})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(js)
	}
}
Ejemplo n.º 28
0
func TestJwt(t *testing.T) {
	// Setup jwt
	c := &JwtAuthConfig{}
	c.Admin.PrivateKey = "Key"
	c.User.PrivateKey = "UserKey"
	j := NewJwtAuth(c)
	tests.Assert(t, j != nil)

	// Setup middleware framework
	n := negroni.New(j)
	tests.Assert(t, n != nil)

	// Create a simple middleware to check if it was called
	called := false
	mw := func(rw http.ResponseWriter, r *http.Request) {
		data := context.Get(r, "jwt")
		tests.Assert(t, data != nil)

		token := data.(*jwt.Token)
		tests.Assert(t, token.Claims["iss"] == "admin")

		called = true

		rw.WriteHeader(http.StatusOK)
	}
	n.UseHandlerFunc(mw)

	// Create test server
	ts := httptest.NewServer(n)

	// Create token with missing 'iss' claim
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims["iss"] = "admin"
	token.Claims["iat"] = time.Now().Unix()
	token.Claims["exp"] = time.Now().Add(time.Second * 10).Unix()

	// Generate qsh
	qshstring := "GET&/"
	hash := sha256.New()
	hash.Write([]byte(qshstring))
	token.Claims["qsh"] = hex.EncodeToString(hash.Sum(nil))

	tokenString, err := token.SignedString([]byte("Key"))
	tests.Assert(t, err == nil)

	// Setup header
	req, err := http.NewRequest("GET", ts.URL, nil)
	tests.Assert(t, err == nil)

	// Miss 'bearer' string
	req.Header.Set("Authorization", "bearer "+tokenString)
	r, err := http.DefaultClient.Do(req)
	tests.Assert(t, err == nil)
	tests.Assert(t, r.StatusCode == http.StatusOK)
	tests.Assert(t, called == true)
}
Ejemplo n.º 29
0
func (u *AccountHandler) createLoginToken(player *ge.PlayerStruct) (string, error) {

	token := jwt.New(jwt.SigningMethodHS256)
	// Set some claims
	token.Claims["id"] = player.ID
	token.Claims["exp"] = time.Now().Add(time.Hour * 1).Unix()
	// Sign and get the complete encoded token as a string
	return token.SignedString([]byte(config.Config.Key))

}
Ejemplo n.º 30
0
func EncodeJwt(secret Secret, claims map[string]interface{}) (EncodedJwt, error) {
	if secret == "" {
		return "", nil
	}

	t := jwt.New(jwt.GetSigningMethod("HS256"))
	t.Claims = claims
	encoded, e := t.SignedString(secret)
	return EncodedJwt(encoded), e
}