本文整理汇总了Golang中github.com/dgrijalva/jwt-go.ParseRSAPrivateKeyFromPEM函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseRSAPrivateKeyFromPEM函数的具体用法?Golang ParseRSAPrivateKeyFromPEM怎么用?Golang ParseRSAPrivateKeyFromPEM使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseRSAPrivateKeyFromPEM函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: generateIDToken
// 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
}
示例2: InitTokens
func InitTokens() (err error) {
signBytes, err := ioutil.ReadFile("config/rsaKey")
if err != nil {
log.Error("Error reading private key from file: ", err)
return
}
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
if err != nil {
log.Error("Error parsing private key from file: ", err)
return
}
verifyBytes, err := ioutil.ReadFile("config/pubKey")
if err != nil {
log.Error("Error reading public key from file: ", err)
return
}
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
if err != nil {
log.Error("Error parsing public key from file: ", err)
return
}
return
}
示例3: ReadPrivateKey
// ReadPrivateKey is a helper function for reading an rsa.PrivateKey from a PEM-encoded file
func ReadPrivateKey(file string) (*rsa.PrivateKey, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
return jwt.ParseRSAPrivateKeyFromPEM(data)
}
示例4: LoadMintKeyByName
// loadMintKeyByName loads a key by filename and stores it in the struct
// The function is threadsafe and panics if the key file is invalid
func LoadMintKeyByName(filename string) {
keyPath := util.GetPaths([]string{filename})[0]
b, err := ioutil.ReadFile(keyPath)
if err != nil {
log.WithFields(log.Fields{
"path": keyPath,
}).Panic("Failed to load mint key: ", err)
}
k, err := jwt.ParseRSAPrivateKeyFromPEM(b)
if err != nil {
log.WithFields(log.Fields{
"path": keyPath,
}).Panic("Failed to parse mint key: ", err)
}
log.WithFields(log.Fields{
"path": keyPath,
}).Debugf("Successfully loaded mint key from %s", keyPath)
// Store only after we are sure loading was good
mint.Lock()
defer mint.Unlock()
mint.Key = k
mint.From = keyPath
}
示例5: ReadPrivateKeyFromPEM
// ReadPrivateKeyFromPEM is a helper function for reading a private key from a PEM-encoded file
func ReadPrivateKeyFromPEM(data []byte) (interface{}, error) {
if key, err := jwt.ParseRSAPrivateKeyFromPEM(data); err == nil {
return key, nil
}
if key, err := jwt.ParseECPrivateKeyFromPEM(data); err == nil {
return key, nil
}
return nil, fmt.Errorf("data does not contain a valid RSA or ECDSA private key")
}
示例6: NewAuthServer
func NewAuthServer(rsaPrivateKey string) (*authServer, error) {
key, err := ioutil.ReadFile(rsaPrivateKey)
if err != nil {
return nil, fmt.Errorf("Error reading the jwt private key: %s", err)
}
parsedKey, err := jwt.ParseRSAPrivateKeyFromPEM(key)
if err != nil {
return nil, fmt.Errorf("Error parsing the jwt private key: %s", err)
}
return &authServer{parsedKey}, nil
}
示例7: GetPrivateKeyFromPath
func GetPrivateKeyFromPath(path string) *rsa.PrivateKey {
bytes, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(bytes)
if err != nil {
log.Fatal(err)
}
return key
}
示例8: NewToken
// NewToken creates new JWT token for the gien username. It embedds the given
// public key as kontrolKey and signs the token with the private one.
func NewToken(username, private, public string) *jwt.Token {
tknID := uuid.NewV4()
hostname, err := os.Hostname()
if err != nil {
panic(err)
}
if username == "" {
username = "testuser"
}
if testuser := os.Getenv("TESTKEY_USERNAME"); testuser != "" {
username = testuser
}
claims := &kitekey.KiteClaims{
StandardClaims: jwt.StandardClaims{
Issuer: "testuser",
Subject: username,
Audience: hostname,
IssuedAt: time.Now().UTC().Unix(),
Id: tknID.String(),
},
KontrolKey: public,
KontrolURL: "http://localhost:4000/kite",
}
token := jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims)
rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(private))
if err != nil {
panic(err)
}
token.Raw, err = token.SignedString(rsaPrivate)
if err != nil {
panic(err)
}
// verify the token
_, err = jwt.ParseWithClaims(token.Raw, claims, func(*jwt.Token) (interface{}, error) {
return jwt.ParseRSAPublicKeyFromPEM([]byte(public))
})
if err != nil {
panic(err)
}
token.Valid = true
return token
}
示例9: generateToken
// generateToken returns a JWT token string. Please see the URL for details:
// http://tools.ietf.org/html/draft-ietf-oauth-json-web-token-13#section-4.1
func (k *Kontrol) generateToken(aud, username, issuer string, kp *KeyPair) (string, error) {
uniqKey := aud + username + issuer + kp.ID
k.tokenCacheMu.Lock()
defer k.tokenCacheMu.Unlock()
signed, ok := k.tokenCache[uniqKey]
if ok {
return signed, nil
}
rsaPrivate, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(kp.Private))
if err != nil {
return "", err
}
now := time.Now().UTC()
claims := &kitekey.KiteClaims{
StandardClaims: jwt.StandardClaims{
Issuer: issuer,
Subject: username,
Audience: aud,
ExpiresAt: now.Add(k.tokenTTL()).Add(k.tokenLeeway()).UTC().Unix(),
IssuedAt: now.Add(-k.tokenLeeway()).UTC().Unix(),
Id: uuid.NewV4().String(),
},
}
if !k.TokenNoNBF {
claims.NotBefore = now.Add(-k.tokenLeeway()).Unix()
}
signed, err = jwt.NewWithClaims(jwt.GetSigningMethod("RS256"), claims).SignedString(rsaPrivate)
if err != nil {
return "", errors.New("Server error: Cannot generate a token")
}
// cache our token
k.tokenCache[uniqKey] = signed
// cache invalidation, because we cache the token in tokenCache we need to
// invalidate it expiration time. This was handled usually within JWT, but
// now we have to do it manually for our own cache.
time.AfterFunc(TokenTTL-TokenLeeway, func() {
k.tokenCacheMu.Lock()
defer k.tokenCacheMu.Unlock()
delete(k.tokenCache, uniqKey)
})
return signed, nil
}
示例10: ReadPublicKey
// ReadPublicKey is a helper function for reading an rsa.PublicKey from a PEM-encoded file
// Reads public keys from both public and private key files
func ReadPublicKey(file string) (*rsa.PublicKey, error) {
data, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
if privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(data); err == nil {
return &privateKey.PublicKey, nil
}
return jwt.ParseRSAPublicKeyFromPEM(data)
}
示例11: ParseTestPrivateKey
func ParseTestPrivateKey() interface{} {
keyBytes, err := ioutil.ReadFile("../test_utils/private.pem")
if err != nil {
log.Fatal("Failed to parse private key.", err)
}
privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(keyBytes)
if err != nil {
log.Fatal("Failed to parse private key.", err)
}
return privateKey
}
示例12: parsePrivateKey
func (t *JwtToken) parsePrivateKey(keyPath string) error {
if pem, err := ioutil.ReadFile(keyPath); err != nil {
return err
} else {
if privKey, err := libjwt.ParseRSAPrivateKeyFromPEM(pem); err != nil {
return err
} else {
t.privKey = privKey
return nil
}
}
}
示例13: init
func init() {
signBytes, err := ioutil.ReadFile(privKeyPath)
fatal(err)
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
fatal(err)
verifyBytes, err := ioutil.ReadFile(pubKeyPath)
fatal(err)
verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
fatal(err)
}
示例14: showDevAuth
func showDevAuth() {
currentKeyBytes, _ := ioutil.ReadFile(config.GetStr(setting.JWT_RSA_KEY_LOCATION))
currentKey, err1 := jwt.ParseRSAPrivateKeyFromPEM(currentKeyBytes)
if err1 != nil {
log.Panic(err1)
}
token := jwt.New(jwt.SigningMethodRS512)
// Set some claims
token.Claims["userId"] = `eeee1df4-9fae-4e32-98c1-88f850a00001`
token.Claims["exp"] = time.Now().Add(time.Minute * 60 * 24 * 30).Unix()
// Sign and get the complete encoded token as a string
tokenString, _ := token.SignedString(currentKey)
fmt.Println("Please put the following string into http 'Authorization' header:")
fmt.Println(tokenString)
}
示例15: TestCreateTrackerQueryREST
func TestCreateTrackerQueryREST(t *testing.T) {
resource.Require(t, resource.Database)
privatekey, err := jwt.ParseRSAPrivateKeyFromPEM([]byte(almtoken.RSAPrivateKey))
if err != nil {
t.Fatal("Could not parse Key ", err)
}
service := goa.New("API")
controller := NewTrackerController(service, gormapplication.NewGormDB(DB), RwiScheduler)
payload := app.CreateTrackerAlternatePayload{
URL: "http://api.github.com",
Type: "github",
}
_, tracker := test.CreateTrackerCreated(t, nil, nil, controller, &payload)
jwtMiddleware := goajwt.New(&privatekey.PublicKey, nil, app.NewJWTSecurity())
app.UseJWTMiddleware(service, jwtMiddleware)
controller2 := NewTrackerqueryController(service, gormapplication.NewGormDB(DB), RwiScheduler)
app.MountTrackerqueryController(service, controller2)
server := httptest.NewServer(service.Mux)
tqPayload := fmt.Sprintf(`{"query": "abcdefgh", "schedule": "1 1 * * * *", "trackerID": "%s"}`, tracker.ID)
trackerQueryCreateURL := "/api/trackerqueries"
req, _ := http.NewRequest("POST", server.URL+trackerQueryCreateURL, strings.NewReader(tqPayload))
jwtToken := getValidAuthHeader(t, privatekey)
req.Header.Set("Authorization", jwtToken)
client := http.Client{}
res, err := client.Do(req)
if err != nil {
t.Fatalf("Server error %s", err)
}
if res.StatusCode != http.StatusCreated {
t.Fatalf("Expected a 201 Created response, got %d", res.StatusCode)
}
server.Close()
}