-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
A minimal gRPC credentials implementation for the HTTP basic authenti…
…cation scheme
- Loading branch information
1 parent
b6dbda4
commit f37a8cb
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package basic | ||
|
||
import ( | ||
"context" | ||
"encoding/base64" | ||
"fmt" | ||
"strings" | ||
|
||
"google.golang.org/grpc/credentials" | ||
"google.golang.org/grpc/metadata" | ||
) | ||
|
||
const ( | ||
mdKey = "authorization" | ||
mdValuePrefix = "Basic " | ||
) | ||
|
||
type Credentials struct { | ||
UserID string | ||
Password string | ||
} | ||
|
||
func (c Credentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { | ||
ri, _ := credentials.RequestInfoFromContext(ctx) | ||
if err := credentials.CheckSecurityLevel(ri.AuthInfo, credentials.PrivacyAndIntegrity); err != nil { | ||
return nil, fmt.Errorf("unable to transfer basic.Credentials PerRPCCredentials: %v", err) | ||
} | ||
return map[string]string{ | ||
mdKey: mdValuePrefix + base64.StdEncoding.EncodeToString([]byte(c.UserID+":"+c.Password)), | ||
}, nil | ||
} | ||
|
||
func (c Credentials) RequireTransportSecurity() bool { | ||
return true | ||
} | ||
|
||
func NewPerRPCCredentials(userID, password string) credentials.PerRPCCredentials { | ||
return Credentials{UserID: userID, Password: password} | ||
} | ||
|
||
func CredentialsFromContext(ctx context.Context) (Credentials, error) { | ||
var c Credentials | ||
mv := metadata.ValueFromIncomingContext(ctx, mdKey) | ||
if mv == nil || len(mv) == 0 { | ||
return c, fmt.Errorf("basic auth credentials metadata key not found in context") | ||
} | ||
decodedCreds, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(mv[0], mdValuePrefix)) | ||
if err != nil { | ||
return c, err | ||
} | ||
c.UserID, c.Password, _ = strings.Cut(string(decodedCreds), ":") | ||
return c, nil | ||
} |