本文整理汇总了Golang中github.com/coreos/go-oidc/jose.NewSignedJWT函数的典型用法代码示例。如果您正苦于以下问题:Golang NewSignedJWT函数的具体用法?Golang NewSignedJWT怎么用?Golang NewSignedJWT使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewSignedJWT函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Generate
// Generate creates a Capabilities Token given some configuration values.
// See https://www.twilio.com/docs/api/client/capability-tokens for details.
func Generate(c Capabilities, expires time.Duration) (string, error) {
signer := jose.NewSignerHMAC("", []byte(c.AuthToken))
claims := jose.Claims{}
claims.Add("iss", c.AccountSid)
claims.Add("exp", Clock.Now().Add(expires).Unix())
scopes := []string{}
if c.AllowClientOutgoing != "" {
scope := fmt.Sprintf("scope:client:outgoing?appSid=%s", c.AllowClientOutgoing)
if c.AllowClientIncoming != "" {
scope += fmt.Sprintf("&clientName=%s", c.AllowClientIncoming)
}
scopes = append(scopes, scope)
}
if c.AllowClientIncoming != "" {
scopes = append(scopes, fmt.Sprintf("scope:client:incoming?clientName=%s", c.AllowClientIncoming))
}
claims.Add("scope", strings.Join(scopes, " "))
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
return "", err
}
return jwt.Encode(), nil
}
示例2: TestGetClientIDFromAuthorizedRequest
func TestGetClientIDFromAuthorizedRequest(t *testing.T) {
now := time.Now()
tomorrow := now.Add(24 * time.Hour)
privKey, err := key.GeneratePrivateKey()
if err != nil {
t.Fatalf("Failed to generate private key, error=%v", err)
}
signer := privKey.Signer()
makeToken := func(iss, sub, aud string, iat, exp time.Time) string {
claims := oidc.NewClaims(iss, sub, aud, iat, exp)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
t.Fatalf("Failed to generate JWT, error=%v", err)
}
return jwt.Encode()
}
tests := []struct {
header string
wantClient string
wantErr bool
}{
{
header: fmt.Sprintf("BEARER %s", makeToken("iss", "CLIENT_ID", "", now, tomorrow)),
wantClient: "CLIENT_ID",
wantErr: false,
},
{
header: fmt.Sprintf("BEARER %s", makeToken("iss", "", "", now, tomorrow)),
wantErr: true,
},
}
for i, tt := range tests {
req := &http.Request{
Header: http.Header{
"Authorization": []string{tt.header},
},
}
gotClient, err := getClientIDFromAuthorizedRequest(req)
if tt.wantErr {
if err == nil {
t.Errorf("case %d: want non-nil err", i)
}
continue
}
if err != nil {
t.Errorf("case %d: got err: %q", i, err)
continue
}
if gotClient != tt.wantClient {
t.Errorf("case %d: want=%v, got=%v", i, tt.wantClient, gotClient)
}
}
}
示例3: ClientCredsToken
func (s *Server) ClientCredsToken(creds oidc.ClientCredentials) (*jose.JWT, error) {
ok, err := s.ClientIdentityRepo.Authenticate(creds)
if err != nil {
log.Errorf("Failed fetching client %s from repo: %v", creds.ID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
if !ok {
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
}
signer, err := s.KeyManager.Signer()
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
now := time.Now()
exp := now.Add(s.SessionManager.ValidityWindow)
claims := oidc.NewClaims(s.IssuerURL.String(), creds.ID, creds.ID, now, exp)
claims.Add("name", creds.ID)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
log.Infof("Client token sent: clientID=%s", creds.ID)
return jwt, nil
}
示例4: Token
func (s *grpcServer) Token(userID, clientID string, iat, exp time.Time) (*jose.JWT, string, error) {
signer, err := s.server.KeyManager.Signer()
if err != nil {
log.Errorf("grpc.go: Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
user, err := s.server.UserRepo.Get(nil, userID)
if err != nil {
log.Errorf("grpc.go: Failed to fetch user %q from repo: %v: ", userID, err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
claims := oidc.NewClaims(s.server.IssuerURL.String(), userID, clientID, iat, exp)
user.AddToClaims(claims)
if user.Admin {
claims.Add(OtsimoUserTypeClaim, "adm")
}
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("grpc.go: Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
refreshToken, err := s.server.RefreshTokenRepo.Create(user.ID, clientID)
if err != nil {
log.Errorf("grpc.go: Failed to generate refresh token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
return jwt, refreshToken, nil
}
示例5: SendResetPasswordEmail
// SendResetPasswordEmail sends a password reset email to the user specified by the email addresss, containing a link with a signed token which can be visitied to initiate the password change/reset process.
// This method DOES NOT check for client ID, redirect URL validity - it is expected that upstream users have already done so.
// If there is no emailer is configured, the URL of the aforementioned link is returned, otherwise nil is returned.
func (u *UserEmailer) SendResetPasswordEmail(email string, redirectURL url.URL, clientID string) (*url.URL, error) {
usr, err := u.ur.GetByEmail(nil, email)
if err == user.ErrorNotFound {
log.Errorf("No Such user for email: %q", email)
return nil, err
}
if err != nil {
log.Errorf("Error getting user: %q", err)
return nil, err
}
pwi, err := u.pwi.Get(nil, usr.ID)
if err == user.ErrorNotFound {
// TODO(bobbyrullo): In this case, maybe send a different email explaining that
// they don't have a local password.
log.Errorf("No Password for userID: %q", usr.ID)
return nil, err
}
if err != nil {
log.Errorf("Error getting password: %q", err)
return nil, err
}
signer, err := u.signerFn()
if err != nil || signer == nil {
log.Errorf("error getting signer: %v (%v)", err, signer)
return nil, err
}
passwordReset := user.NewPasswordReset(usr, pwi.Password, u.issuerURL,
clientID, redirectURL, u.tokenValidityWindow)
jwt, err := jose.NewSignedJWT(passwordReset.Claims, signer)
if err != nil {
log.Errorf("error constructing or signing PasswordReset JWT: %v", err)
return nil, err
}
token := jwt.Encode()
resetURL := u.passwordResetURL
q := resetURL.Query()
q.Set("token", token)
resetURL.RawQuery = q.Encode()
if u.emailer != nil {
err = u.emailer.SendMail(u.fromAddress, "Reset your password.", "password-reset",
map[string]interface{}{
"email": usr.Email,
"link": resetURL.String(),
}, usr.Email)
if err != nil {
log.Errorf("error sending password reset email %v: ", err)
}
return nil, err
}
return &resetURL, nil
}
示例6: makeUserToken
func makeUserToken(issuerURL url.URL, userID, clientID string, expires time.Duration, privKey *key.PrivateKey) string {
signer := key.NewPrivateKeySet([]*key.PrivateKey{testPrivKey},
time.Now().Add(time.Minute)).Active().Signer()
claims := oidc.NewClaims(issuerURL.String(), userID, clientID, time.Now(), time.Now().Add(expires))
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
panic(fmt.Sprintf("could not make token: %v", err))
}
return jwt.Encode()
}
示例7: generateToken
func (op *oidcProvider) generateToken(t *testing.T, iss, sub, aud string, usernameClaim, value string, iat, exp time.Time) string {
signer := op.privKey.Signer()
claims := oidc.NewClaims(iss, sub, aud, iat, exp)
claims.Add(usernameClaim, value)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
t.Fatalf("Cannot generate token: %v", err)
return ""
}
return jwt.Encode()
}
示例8: Token
// Token serializes the EmailVerification into a signed JWT.
func (e EmailVerification) Token(signer jose.Signer) (string, error) {
if signer == nil {
return "", errors.New("no signer")
}
jwt, err := jose.NewSignedJWT(e.claims, signer)
if err != nil {
return "", err
}
return jwt.Encode(), nil
}
示例9: Token
// Token serializes the PasswordReset into a signed JWT.
func (e PasswordReset) Token(signer jose.Signer) (string, error) {
if signer == nil {
return "", errors.New("no signer")
}
jwt, err := jose.NewSignedJWT(e.claims, signer)
if err != nil {
return "", err
}
return jwt.Encode(), nil
}
示例10: RefreshToken
func (s *Server) RefreshToken(creds oidc.ClientCredentials, token string) (*jose.JWT, error) {
ok, err := s.ClientIdentityRepo.Authenticate(creds)
if err != nil {
log.Errorf("Failed fetching client %s from repo: %v", creds.ID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
if !ok {
log.Errorf("Failed to Authenticate client %s", creds.ID)
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
}
userID, err := s.RefreshTokenRepo.Verify(creds.ID, token)
switch err {
case nil:
break
case refresh.ErrorInvalidToken:
return nil, oauth2.NewError(oauth2.ErrorInvalidRequest)
case refresh.ErrorInvalidClientID:
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
default:
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
user, err := s.UserRepo.Get(nil, userID)
if err != nil {
// The error can be user.ErrorNotFound, but we are not deleting
// user at this moment, so this shouldn't happen.
log.Errorf("Failed to fetch user %q from repo: %v: ", userID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
signer, err := s.KeyManager.Signer()
if err != nil {
log.Errorf("Failed to refresh ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
now := time.Now()
expireAt := now.Add(session.DefaultSessionValidityWindow)
claims := oidc.NewClaims(s.IssuerURL.String(), user.ID, creds.ID, now, expireAt)
user.AddToClaims(claims)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
log.Infof("New token sent: clientID=%s", creds.ID)
return jwt, nil
}
示例11: signedClaimsToken
func (u *UserEmailer) signedClaimsToken(claims jose.Claims) (string, error) {
signer, err := u.signerFn()
if err != nil || signer == nil {
log.Errorf("error getting signer: %v (%v)", err, signer)
return "", err
}
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("error constructing or signing a JWT: %v", err)
return "", err
}
return jwt.Encode(), nil
}
示例12: generateToken
func generateToken(t *testing.T, op *oidctesting.OIDCProvider, iss, sub, aud string, usernameClaim, value, groupsClaim string, groups interface{}, iat, exp time.Time) string {
signer := op.PrivKey.Signer()
claims := oidc.NewClaims(iss, sub, aud, iat, exp)
claims.Add(usernameClaim, value)
if groups != nil && groupsClaim != "" {
claims.Add(groupsClaim, groups)
}
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
t.Fatalf("Cannot generate token: %v", err)
return ""
}
return jwt.Encode()
}
示例13: createJWTToken
//Creates a signed JWT token for the requesting subject and issuer URL
func createJWTToken(subject string, issuerUrl string, tokenttl time.Duration, scopesMap map[string]struct{}, unsignedToken bool) (jwt *jose.JWT, err error) {
privateKey, err := privateKey()
if err != nil {
return nil, base.HTTPErrorf(http.StatusInternalServerError, "Error getting private RSA Key")
}
now := time.Now()
expiresIn := tokenttl
expiryTime := now.Add(expiresIn)
cl := jose.Claims{
"sub": subject,
"iat": now.Unix(),
"exp": expiryTime.Unix(),
"iss": issuerUrl,
"aud": testProviderAud,
}
if _, ok := scopesMap["email"]; ok {
cl["email"] = subject + "@syncgatewayoidctesting.com"
}
if _, ok := scopesMap["profile"]; ok {
cl["nickname"] = "slim jim"
}
signer := jose.NewSignerRSA(testProviderKeyIdentifier, *privateKey)
if !unsignedToken {
jwt, err = jose.NewSignedJWT(cl, signer)
if err != nil {
return nil, err
}
} else {
header := jose.JOSEHeader{
"alg": signer.Alg(),
"kid": signer.ID(),
}
unsignedJWT, err := jose.NewJWT(header, cl)
if err != nil {
return nil, err
}
jwt = &unsignedJWT
}
return
}
示例14: SendEmailVerification
// SendEmailVerification sends an email to the user with the given userID containing a link which when visited marks the user as having had their email verified.
// If there is no emailer is configured, the URL of the aforementioned link is returned, otherwise nil is returned.
func (u *UserEmailer) SendEmailVerification(userID, clientID string, redirectURL url.URL) (*url.URL, error) {
usr, err := u.ur.Get(nil, userID)
if err == user.ErrorNotFound {
log.Errorf("No Such user for ID: %q", userID)
return nil, err
}
if err != nil {
log.Errorf("Error getting user: %q", err)
return nil, err
}
ev := user.NewEmailVerification(usr, clientID, u.issuerURL, redirectURL, u.tokenValidityWindow)
signer, err := u.signerFn()
if err != nil || signer == nil {
log.Errorf("error getting signer: %v (signer: %v)", err, signer)
return nil, err
}
jwt, err := jose.NewSignedJWT(ev.Claims, signer)
if err != nil {
log.Errorf("error constructing or signing EmailVerification JWT: %v", err)
return nil, err
}
token := jwt.Encode()
verifyURL := u.verifyEmailURL
q := verifyURL.Query()
q.Set("token", token)
verifyURL.RawQuery = q.Encode()
if u.emailer != nil {
err = u.emailer.SendMail(u.fromAddress, "Please verify your email address.", "verify-email",
map[string]interface{}{
"email": usr.Email,
"link": verifyURL.String(),
}, usr.Email)
if err != nil {
log.Errorf("error sending email verification email %v: ", err)
}
return nil, err
}
return &verifyURL, nil
}
示例15: TestHandleVerifyEmailResend
func TestHandleVerifyEmailResend(t *testing.T) {
now := time.Now()
tomorrow := now.Add(24 * time.Hour)
yesterday := now.Add(-24 * time.Hour)
privKey, err := key.GeneratePrivateKey()
if err != nil {
t.Fatalf("Failed to generate private key, error=%v", err)
}
signer := privKey.Signer()
pubKey := *key.NewPublicKey(privKey.JWK())
keysFunc := func() ([]key.PublicKey, error) {
return []key.PublicKey{pubKey}, nil
}
makeToken := func(iss, sub, aud string, iat, exp time.Time) string {
claims := oidc.NewClaims(iss, sub, aud, iat, exp)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
t.Fatalf("Failed to generate JWT, error=%v", err)
}
return jwt.Encode()
}
tests := []struct {
bearerJWT string
userJWT string
redirectURL url.URL
wantCode int
verifyEmailUserID string
}{
{
// The happy case
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"ID-1", testClientID, now, tomorrow),
redirectURL: testRedirectURL,
wantCode: http.StatusOK,
},
{
// Already verified
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"ID-1", testClientID, now, tomorrow),
redirectURL: testRedirectURL,
wantCode: http.StatusBadRequest,
verifyEmailUserID: "ID-1",
},
{
// Expired userJWT
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"ID-1", testClientID, now, yesterday),
redirectURL: testRedirectURL,
wantCode: http.StatusUnauthorized,
},
{
// Client ID is unknown
bearerJWT: makeToken(testIssuerURL.String(),
"fakeclientid", testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"ID-1", testClientID, now, tomorrow),
redirectURL: testRedirectURL,
wantCode: http.StatusBadRequest,
},
{
// No sub in user JWT
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"", testClientID, now, tomorrow),
redirectURL: testRedirectURL,
wantCode: http.StatusBadRequest,
},
{
// Unknown user
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"NonExistent", testClientID, now, tomorrow),
redirectURL: testRedirectURL,
wantCode: http.StatusBadRequest,
},
{
// No redirect URL
bearerJWT: makeToken(testIssuerURL.String(),
testClientID, testClientID, now, tomorrow),
userJWT: makeToken(testIssuerURL.String(),
"ID-1", testClientID, now, tomorrow),
redirectURL: url.URL{},
wantCode: http.StatusBadRequest,
},
}
for i, tt := range tests {
//.........这里部分代码省略.........