Esempio n. 1
3
func GetUserInfo(res http.ResponseWriter, req *http.Request) {
	AuthKey := http.CanonicalHeaderKey("authorization")
	tokenString := strings.Replace(req.Header.Get(AuthKey), "Bearer ", "", -1)
	// fmt.Println(tokenString)

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		fmt.Println(token)
		return loadData("demo.rsa.pub")
	})

	if err == nil && token.Valid {
		fmt.Println("Your token is valid.  I like your style.")

		rt, _ := json.Marshal(Result{http.StatusOK, "Successful", tokenString})
		res.Header().Set("Content-Type", "application/json")
		res.WriteHeader(http.StatusOK)
		res.Write(rt)
	} else {
		fmt.Println("This token is terrible!  I cannot accept this.")
		fmt.Println(err)

		rt, _ := json.Marshal(Result{http.StatusUnauthorized, "Token Unauthorized", tokenString})
		res.Header().Set("Content-Type", "application/json")
		res.WriteHeader(http.StatusUnauthorized)
		res.Write(rt)
	}
}
Esempio n. 2
1
// returns username and boolean indicating if the token was valid
func getAuth(r *http.Request) (string, bool) {
	// check if we have a cookie with our tokenName
	tokenCookie, err := r.Cookie(tokenName)

	if err != nil {
		return "", false
	}

	// validate the token
	token, err := jwt.Parse(tokenCookie.Value, func(token *jwt.Token) (interface{}, error) {
		return verifyKey, nil
	})

	if err == nil && token.Valid {
		str, ok := token.Claims["username"].(string)
		if ok {
			return str, true
		} else {
			log.Print("token.Claims[\"username\"] Not a string.")
			return "", false
		}

	}

	return "", false
}
Esempio n. 3
1
func CheckToken() gin.HandlerFunc {

	return func(c *gin.Context) {

		// request cookie
		tokenCookie, err := c.Request.Cookie("token")

		switch {
		case err == http.ErrNoCookie:
			//c.JSON(http.StatusUnauthorized, gin.H{"message": http.ErrNoCookie.Error()})
			c.HTML(http.StatusUnauthorized, "err.tmpl", gin.H{"message": http.ErrNoCookie.Error()})
			c.Abort()
			return
		case err != nil:
			c.JSON(http.StatusUnauthorized, gin.H{"message": "something is wrong with the cookie"})
		}

		// validate the token
		token, err := jwt.Parse(tokenCookie.Value, func(token *jwt.Token) (interface{}, error) {
			return verifyKey, nil
		})

		switch err.(type) {
		case nil:
			if !token.Valid {
				c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": "StatusUnauthorized"})
				c.Abort()
				return
			}
			data := struct {
				Access   string
				Username string
			}{
				token.Claims["access"].(string),
				token.Claims["username"].(string),
			}
			//c.Set("token", token)
			//c.Set("admin", token.Claims["access"])
			c.Set("data", data)
			c.Next()
		case *jwt.ValidationError:
			vErr := err.(*jwt.ValidationError)
			switch vErr.Errors {
			case jwt.ValidationErrorExpired:
				c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": "token expired"})
				c.Abort()
				return
			default:
				c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": vErr.Errors})
				c.Abort()
				return
			}
		default:
			c.JSON(http.StatusUnauthorized, gin.H{"StatusUnauthorized": err.Error()})
			c.Abort()
			return
		}
	}
}
Esempio n. 4
0
func GetUserFromToken(token string) (*rbac.User, error) {
	_, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("Unexpected signing method")
		}

		expiredText, _ := token.Claims["expired"].(string)

		expiredTime, err := time.Parse(time.RFC3339, expiredText)
		if err != nil {
			log.Error("Fail to parse expired time. Token %v error %s", token, err)
			return nil, err
		}

		if expiredTime.Before(time.Now()) {
			log.Debug("Token is expired. Token %v ", token)
			return nil, errors.New("Token is expired")
		}
		return []byte(signingKey), nil
	})

	if err != nil {
		return nil, err
	} else {
		user := rbac.GetCache(token)
		if user != nil {
			return user, nil
		} else {
			log.Error("User not in the cache. Token %v", token)
			return nil, errors.New("User not in the cache")
		}
	}
}
Esempio n. 5
0
func subjectFromBearerToken(core *roll.Core, r *http.Request) (string, error) {
	//Check for header presence
	authzHeader := r.Header.Get("Authorization")
	if authzHeader == "" {
		return "", errors.New("Authorization header missing from request")
	}

	//Header format should be Bearer token
	parts := strings.SplitAfter(authzHeader, "Bearer")
	if len(parts) != 2 {
		return "", errors.New("Unexpected authorization header format - expecting bearer token")
	}

	//Parse the token
	bearerToken := strings.TrimSpace(parts[1])
	token, err := jwt.Parse(bearerToken, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
	if err != nil {
		return "", err
	}

	//Grab the subject from the claims
	subject, ok := token.Claims["sub"].(string)
	if !ok {
		return "", errors.New("problem with subject claim")
	}

	//Is the subject something other than an empty string?
	if subject == "" {
		return "", errors.New("empty subject claim")
	}

	return subject, nil
}
Esempio n. 6
0
func (k *Kontrol) handleGetKey(r *kite.Request) (interface{}, error) {
	// Only accept requests with kiteKey because we need this info
	// for checking if the key is valid and needs to be regenerated
	if r.Auth.Type != "kiteKey" {
		return nil, fmt.Errorf("Unexpected authentication type: %s", r.Auth.Type)
	}

	t, err := jwt.Parse(r.Auth.Key, kitekey.GetKontrolKey)
	if err != nil {
		return nil, err
	}

	publicKey, ok := t.Claims["kontrolKey"].(string)
	if !ok {
		return nil, errors.New("public key is not passed")
	}

	err = k.keyPair.IsValid(publicKey)
	if err == nil {
		// everything is ok, just return the old one
		return publicKey, nil
	}

	keyPair, err := k.pickKey(r)
	if err != nil {
		return nil, err
	}

	return keyPair.Public, nil
}
Esempio n. 7
0
func (authen *Authen) ParseToken(tokenString string) (*jwt.Token, error) {
	myToken, err := jwt.Parse(tokenString, func(tokenWithin *jwt.Token) (interface{}, error) {
		if _, ok := tokenWithin.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", tokenWithin.Header["alg"])
		}
		if tokenWithin.Method.Alg() != "HS512" {
			return nil, fmt.Errorf("Unexpected signing method string: %v", tokenWithin.Header["alg"])
		}
		exp, ok := tokenWithin.Claims["exp"].(float64)
		if !ok {
			return nil, fmt.Errorf("Token does not contain expiry claim")
		}
		if exp < float64(time.Now().Unix()) {
			return nil, fmt.Errorf("Token expired")
		}
		return authen.privateKey, nil
	})
	if err != nil {
		return nil, err
	}
	if !myToken.Valid {
		return nil, fmt.Errorf("Token is invalid")
	}
	return myToken, err
}
Esempio n. 8
0
func (mgm tokenManager) Extract(tokenString string) (*account.Identity, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return mgm.publicKey, nil
	})
	if err != nil {
		return nil, errors.WithStack(err)
	}

	if !token.Valid {
		return nil, errors.New("Token not valid")
	}

	claimedUUID := token.Claims.(jwt.MapClaims)["sub"]
	if claimedUUID == nil {
		return nil, errors.New("Subject can not be nil")
	}
	// in case of nil UUID, below type casting will fail hence we need above check
	id, err := uuid.FromString(token.Claims.(jwt.MapClaims)["sub"].(string))
	if err != nil {
		return nil, errors.WithStack(err)
	}

	ident := account.Identity{
		ID:       id,
		Username: token.Claims.(jwt.MapClaims)["preferred_username"].(string),
	}

	return &ident, nil
}
func getTokenData(jwtSigningKey string, r *http.Request) (*TokenData, error) {
	encToken, err := r.Cookie(CookieName)
	if err != nil {
		return nil, err
	}

	token, err := jwt.Parse(encToken.Value, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(jwtSigningKey), nil
	})

	if err != nil {
		return nil, err
	}
	if !token.Valid {
		return nil, fmt.Errorf("invalid token")
	}

	userInterface, hasUser := token.Claims["user"]
	roleInterface, hasRole := token.Claims["role"]
	user, userIsStr := userInterface.(string)
	role, roleIsStr := roleInterface.(string)
	if !hasUser || !hasRole || !userIsStr || !roleIsStr {
		// we signed it: this should never happen
		return nil, fmt.Errorf("token missing claims")
	}

	return &TokenData{User: user, Role: role}, nil
}
Esempio n. 10
0
func (m *defaultSessionManager) readToken(r *http.Request) (string, error) {
	tokenString := r.Header.Get(tokenHeader)
	if tokenString == "" {
		return "", nil
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return m.verifyKey, nil
	})
	switch err.(type) {
	case nil:
		if !token.Valid {
			return "", nil
		}

		claims := token.Claims.(jwt.MapClaims)
		houseID := claims["houseID"].(string)

		return houseID, nil
	case *jwt.ValidationError:
		return "", nil
	default:
		return "", errgo.Mask(err)
	}
}
Esempio n. 11
0
// Verify a JWT token using an RSA public key
func VerifyJWTRSA(token, publicKey string) (bool, *jwt.Token, error) {

	var parsedToken *jwt.Token

	// parse token
	state, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {

		// ensure signing method is correct
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, errors.New("unknown signing method")
		}

		parsedToken = token

		// verify
		key, err := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))
		if err != nil {
			return nil, err
		}

		return key, nil
	})

	if err != nil {
		return false, &jwt.Token{}, err
	}

	if !state.Valid {
		return false, &jwt.Token{}, errors.New("invalid jwt token")
	}

	return true, parsedToken, nil
}
Esempio n. 12
0
func Auth(rw http.ResponseWriter, req *http.Request) bool {
	if !config.Config.Auth {
		return true
	}
	tokenString := req.URL.Query().Get("token")

	if len(tokenString) == 0 {
		return false
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return config.Config.ParsedPublicKey, nil
	})
	SetToken(req, token)

	if err != nil {
		common.CheckError(err, 2)
		return false
	}

	if !token.Valid {
		return false
	}

	if config.Config.HostUuidCheck && token.Claims["hostUuid"] != config.Config.HostUuid {
		glog.Infoln("Host UUID mismatch , authentication failed")
		return false
	}

	return true
}
Esempio n. 13
0
func (s *Server) Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		pubKey := s.Tables["divan"].PubKey
		if pubKey == "" {
			c.Next()
			return
		}
		token := c.Query("token")
		if token == "" {
			c.JSON(401, gin.H{"error": "missing token"})
			c.Abort()
			return
		}

		out, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
				return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
			}
			return []byte(pubKey), nil
		})
		if err != nil {
			c.JSON(400, gin.H{"error": err.Error()})
			c.Abort()
			return
		}
		if !out.Valid {
			c.JSON(403, gin.H{"error": "Token invalid"})
			c.Abort()
			return
		}

		c.Set("token", out)
		c.Next()
	}
}
Esempio n. 14
0
// showToken pretty-prints the token on the command line.
func showToken() error {
	// get the token
	tokData, err := loadData(*flagShow)
	if err != nil {
		return fmt.Errorf("Couldn't read token: %v", err)
	}

	// trim possible whitespace from token
	tokData = regexp.MustCompile(`\s*$`).ReplaceAll(tokData, []byte{})
	if *flagDebug {
		fmt.Fprintf(os.Stderr, "Token len: %v bytes\n", len(tokData))
	}

	token, err := jwt.Parse(string(tokData), nil)
	if token == nil {
		return fmt.Errorf("malformed token: %v", err)
	}

	// Print the token details
	fmt.Println("Header:")
	if err := printJSON(token.Header); err != nil {
		return fmt.Errorf("Failed to output header: %v", err)
	}

	fmt.Println("Claims:")
	if err := printJSON(token.Claims); err != nil {
		return fmt.Errorf("Failed to output claims: %v", err)
	}

	return nil
}
Esempio n. 15
0
// Download - file download handler.
func (web *webAPIHandlers) Download(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	bucket := vars["bucket"]
	object := vars["object"]
	token := r.URL.Query().Get("token")

	jwt := initJWT()
	jwttoken, e := jwtgo.Parse(token, func(token *jwtgo.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwtgo.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(jwt.SecretAccessKey), nil
	})
	if e != nil || !jwttoken.Valid {
		writeWebErrorResponse(w, errInvalidToken)
		return
	}
	// Add content disposition.
	w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filepath.Base(object)))

	objInfo, err := web.ObjectAPI.GetObjectInfo(bucket, object)
	if err != nil {
		writeWebErrorResponse(w, err)
		return
	}
	offset := int64(0)
	err = web.ObjectAPI.GetObject(bucket, object, offset, objInfo.Size, w)
	if err != nil {
		/// No need to print error, response writer already written to.
		return
	}
}
Esempio n. 16
0
func (m *defaultSessionManager) readToken(r *http.Request) (int64, error) {
	tokenString := r.Header.Get(tokenHeader)
	if tokenString == "" {
		return 0, nil
	}
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return m.verifyKey, nil
	})
	switch err.(type) {
	case nil:
		if !token.Valid {
			return 0, nil
		}
		token := token.Claims["uid"].(string)
		userID, err := strconv.ParseInt(token, 10, 0)
		if err != nil {
			return 0, nil
		}
		return userID, nil
	case *jwt.ValidationError:
		return 0, nil
	default:
		return 0, errgo.Mask(err)
	}
}
Esempio n. 17
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()
	}
}
Esempio n. 18
0
func TestAuthValidateCodeResponseAuthenticateOk(t *testing.T) {

	core, coreConfig := NewTestCore()
	ln, addr := TestServer(t, core)
	defer ln.Close()

	privateKey, publicKey, err := secrets.GenerateKeyPair()
	assert.Nil(t, err)

	secretsMock := coreConfig.SecretsRepo.(*mocks.SecretsRepo)
	secretsMock.On("RetrievePrivateKeyForApp", "1111-2222-3333333-4444444").Return(privateKey, nil)
	secretsMock.On("RetrievePublicKeyForApp", "1111-2222-3333333-4444444").Return(publicKey, nil)

	var loginCalled = false
	ls := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		loginCalled = true
		w.WriteHeader(http.StatusOK)
	}))
	defer ls.Close()

	//TODO - use a second callback where we serve up a script to extract the page details sent
	//on deny and post those details to another test server.
	var callbackInvoked = false

	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		callbackInvoked = true
		code := r.FormValue("code")
		token, err := jwt.Parse(code, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
		assert.Nil(t, err)
		scope, ok := token.Claims["scope"].(string)
		assert.True(t, ok)
		assert.Equal(t, "xtAuthCode", scope)
	}))
	defer ts.Close()

	lsURL, _ := url.Parse(ls.URL)

	returnVal := roll.Application{
		DeveloperEmail:  "*****@*****.**",
		ClientID:        "1111-2222-3333333-4444444",
		ApplicationName: "fight club",
		ClientSecret:    "not for browser clients",
		RedirectURI:     ts.URL,
		LoginProvider:   "xtrac://" + lsURL.Host,
	}

	appRepoMock := coreConfig.ApplicationRepo.(*mocks.ApplicationRepo)
	appRepoMock.On("SystemRetrieveApplication", "1111-2222-3333333-4444444").Return(&returnVal, nil)

	_, err = http.PostForm(addr+"/oauth2/validate",
		url.Values{"username": {"x"},
			"password":      {"y"},
			"authorize":     {"allow"},
			"response_type": {"code"},
			"client_id":     {"1111-2222-3333333-4444444"}})
	assert.Nil(t, err)
	assert.True(t, callbackInvoked)
	assert.True(t, loginCalled)
}
Esempio n. 19
0
func TestPWGrantLoginOk(t *testing.T) {
	core, coreConfig := NewTestCore()
	ln, addr := TestServer(t, core)
	defer ln.Close()

	var loginCalled = false
	ls := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		loginCalled = true
		w.WriteHeader(http.StatusOK)
	}))
	defer ls.Close()

	lsURL, _ := url.Parse(ls.URL)

	returnVal := roll.Application{
		DeveloperEmail:  "*****@*****.**",
		ClientID:        "1111-2222-3333333-4444444",
		ApplicationName: "fight club",
		ClientSecret:    "not for browser clients",
		RedirectURI:     "http://localhost:3000/ab",
		LoginProvider:   "xtrac://" + lsURL.Host,
	}

	appRepoMock := coreConfig.ApplicationRepo.(*mocks.ApplicationRepo)
	appRepoMock.On("SystemRetrieveApplication", "1111-2222-3333333-4444444").Return(&returnVal, nil)

	privateKey, publicKey, err := secrets.GenerateKeyPair()
	assert.Nil(t, err)

	secretsMock := coreConfig.SecretsRepo.(*mocks.SecretsRepo)
	secretsMock.On("RetrievePrivateKeyForApp", "1111-2222-3333333-4444444").Return(privateKey, nil)
	secretsMock.On("RetrievePublicKeyForApp", "1111-2222-3333333-4444444").Return(publicKey, nil)

	resp, err := http.PostForm(addr+OAuth2TokenBaseURI,
		url.Values{"grant_type": {"password"},
			"client_id":     {"1111-2222-3333333-4444444"},
			"client_secret": {"not for browser clients"},
			"username":      {"abc"},
			"password":      {"xxxxxxxx"}})

	assert.True(t, loginCalled)
	assert.Nil(t, err)
	assert.Equal(t, http.StatusOK, resp.StatusCode)

	body := responseAsString(t, resp)
	var jsonResponse accessTokenResponse
	err = json.Unmarshal([]byte(body), &jsonResponse)
	assert.Nil(t, err)
	assert.True(t, jsonResponse.AccessToken != "")
	assert.True(t, jsonResponse.TokenType == "Bearer")

	token, err := jwt.Parse(jsonResponse.AccessToken, rolltoken.GenerateKeyExtractionFunction(core.SecretsRepo))
	assert.Nil(t, err)
	fmt.Println(token.Claims)
	assert.Equal(t, "1111-2222-3333333-4444444", token.Claims["aud"].(string))
	assert.Equal(t, "abc", token.Claims["sub"].(string))
	assert.Equal(t, "", token.Claims["scope"].(string))
}
Esempio n. 20
0
func parseRequestToken(tokenString string, parsedPublicKey interface{}) (*jwt.Token, error) {
	if tokenString == "" {
		return nil, fmt.Errorf("No JWT token provided")
	}

	return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return parsedPublicKey, nil
	})
}
Esempio n. 21
0
func Authenticate() gin.HandlerFunc {
	return func(c *gin.Context) {
		db := c.MustGet("db").(gorm.DB)
		config = c.MustGet("config").(models.Configuration)

		tokenString := c.Request.Header.Get("X-Authentication-Token")

		if tokenString == "" {
			response := make(map[string]string)
			response["error"] = "Invalid credentials."
			c.JSON(401, response)
			c.Abort(401)
		} else {
			token, err := jwt.Parse(tokenString, verify)

			if err != nil {
				log.Fatal(err)
			} else {
				if token.Valid {

					now := time.Now().UTC()
					expiration, err := time.Parse(time.RFC3339, token.Claims["life"].(string))

					if err != nil {
						log.Fatal(err)
					}

					if now.After(expiration) {
						response := make(map[string]string)
						response["error"] = "Invalid credentials."
						c.JSON(401, response)
						c.Abort(401)
					}

					var user models.User

					db.First(&user, token.Claims["id"])

					if user.Username == "" {
						response := make(map[string]string)
						response["error"] = "Someone f****d up."
						c.JSON(500, response)
						c.Abort(500)
					} else {
						c.Set("consumer", user)
						c.Next()
					}
				} else {
					response := make(map[string]string)
					response["error"] = "Someone f****d up."
					c.JSON(500, response)
					c.Abort(500)
				}
			}
		}
	}
}
func RequireTokenAuthentication(r render.Render, req *http.Request) {
	token, err := jwt.Parse(req.Header.Get("Authorization"), GetParsKey)

	if err == nil && token.Valid && !IsInBlacklist(req.Header.Get("Authorization")) {
		return
	} else {
		r.JSON(http.StatusUnauthorized, map[string]string{"message": "Authen Fail"})
	}
}
Esempio n. 23
0
func newRestServerAPI(datasource *datasource.DataSource) *restServerAPI {
	rest := grest.NewApi()
	rest.Use(grest.DefaultDevStack...)

	rest.Use(&grest.CorsMiddleware{
		RejectNonCorsRequests: false,
		OriginValidator: func(origin string, request *grest.Request) bool {
			// TODO Origin check
			return true
		},
		AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowedHeaders: []string{
			"Accept", "Content-Type", "X-Custom-Header", "Origin", "Authorization"},
		AccessControlAllowCredentials: true,
		AccessControlMaxAge:           3600,
	})

	var bearerAuthMiddleware = &AuthBearerMiddleware{
		Realm: "RestAuthentication",
		Authenticator: func(token string) string {
			parsedToken, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
				if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
					return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
				}
				return datasource.ConfigByteArray("TOKEN_SIGN_KEY"), nil
			})

			if err == nil && parsedToken.Valid {
				return parsedToken.Claims["email"].(string)
			} else {
				return ""
			}
		},
		Authorizer: func(request *grest.Request, userID string) bool {
			user, err := datasource.UserByEmail(userID)
			if err != nil {
				logging.Log(debugTag, "Couldn't fetch user for userID=%s", userID)
				return false
			}
			request.Env["REMOTE_USER_OBJECT"] = user

			return true
		},
	}
	rest.Use(&grest.IfMiddleware{
		Condition: func(request *grest.Request) bool {
			return request.URL.Path != "/login"
		},
		IfTrue: bearerAuthMiddleware,
	})

	return &restServerAPI{
		rest: rest,
		ds:   datasource,
	}
}
func Logout(r render.Render, params martini.Params, req *http.Request) {
	token, err := jwt.Parse(req.Header.Get("Authorization"), authentication.GetParsKey)

	if err == nil && token.Valid {
		tokenString := req.Header.Get("Authorization")
		authentication.Logout(tokenString, token)
	}

	r.JSON(200, map[string]string{"message": "SUCCESS"})
}
Esempio n. 25
0
func ParseAccessToken(tokenString string) (*jwt.Token, error) {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// since we only use the one private key to sign the tokens,
		// we also only use its public counter part to verify

		return verifyKey, nil
	})
	return token, err

}
Esempio n. 26
0
func main() {

	flag.Parse()

	secret := flag.Arg(0)

	reader := bufio.NewReader(os.Stdin)

	// decode
	if *action {
		s, err := ioutil.ReadAll(reader)

		if err != nil {
			handleError(err)
		}

		token, err := jwt.Parse(strings.TrimSpace(string(s)), func(t *jwt.Token) (interface{}, error) {
			if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, fmt.Errorf("不予許的加密算法 %s \n", t.Header["alg"])
			}

			return []byte(secret), nil
		})

		if err != nil {
			handleError(err)
		}

		result, err := json.Marshal(token.Claims)

		if err != nil {
			handleError(err)
		}

		fmt.Println(string(result))

	} else {

		build := jwt.New(jwt.SigningMethodHS256)

		err := json.NewDecoder(reader).Decode(&build.Claims)
		if err != nil {
			handleError(err)
		}

		token, err := build.SignedString([]byte(secret))

		if err != nil {
			handleError(err)
		}

		fmt.Println(token)
	}

}
func (suite *AuthenticationBackendTestSuite) TestIsInBlacklist(c *C) {
	authBackend := authentication.InitJWTAuthenticationBackend()
	tokenString, err := authBackend.GenerateToken("1234")
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return authBackend.PublicKey, nil
	})
	err = authBackend.Logout(tokenString, token)
	assert.Nil(t, err)

	assert.True(t, authBackend.IsInBlacklist(tokenString))
}
Esempio n. 28
0
func validateToken(tokenString string) (*jwt.Token, error) {

	tokenString = strings.Replace(tokenString, "Bearer ", "", 1)
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte("CAmeRAFiveSevenNineNine"), nil
	})
	return token, err
}
Esempio n. 29
0
func IsAllowed(w http.ResponseWriter, r *http.Request) bool {
	logger.Log("Checking whether admintoken is set", logger.DEBUG)
	client_token := r.Header.Get("admintoken")
	if client_token == "" {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusForbidden)
		json.NewEncoder(w).Encode(map[string]string{"error": "token not set"})
		logger.Log("Token 'admintoken' not set", logger.WARN)
		return false
	}

	// validate the token
	token, err := jwt.Parse(client_token, func(token *jwt.Token) (interface{}, error) {
		return verifyKey, nil
	})

	switch err.(type) {
	case nil: //no error
		if !token.Valid { // may be invalid
			w.WriteHeader(http.StatusUnauthorized)
			json.NewEncoder(w).Encode(map[string]string{"error": "token is invalid"})
			logger.Log("Token is invalid", logger.WARN)
			return false
		}
		return true

	case *jwt.ValidationError: // something was wrong during the validation
		vErr := err.(*jwt.ValidationError)

		switch vErr.Errors {
		case jwt.ValidationErrorExpired:
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(http.StatusUnauthorized)
			json.NewEncoder(w).Encode(map[string]string{"error": "token expired"})
			logger.Log("Token expired", logger.WARN)
			return false

		default:
			w.Header().Set("Content-Type", "application/json; charset=UTF-8")
			w.WriteHeader(http.StatusUnauthorized)
			json.NewEncoder(w).Encode(map[string]string{"error": "error while parsing token "})
			logger.Log("Error while parsing token: "+token.Raw, logger.WARN)
			return false
		}

	default: // something else went wrong
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusInternalServerError)
		json.NewEncoder(w).Encode(map[string]string{"error": "something went wrong"})
		logger.Log("Something with this token is wrong: "+token.Raw, logger.ERROR)
		return false
	}
}
Esempio n. 30
0
func (a *Authorizer) Validate(myToken string) bool {
	token, err := jwt.Parse(myToken, func(token *jwt.Token) (interface{}, error) {
		return SignKey, nil
	})
	foo := token.Claims["foo"]

	if err == nil && token.Valid && foo == FooClaim {
		return true
	}

	return false
}