Add ContextWithToken (#1407)

* Add ContextWithToken

* Tidying up BearerScheme

Co-authored-by: Ben Toogood <ben@micro.mu>
This commit is contained in:
ben-toogood 2020-03-25 11:20:53 +00:00 committed by GitHub
parent 35e2a68a98
commit 1057ef6acb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 16 additions and 22 deletions

View File

@ -9,11 +9,6 @@ import (
"github.com/micro/go-micro/v2/auth" "github.com/micro/go-micro/v2/auth"
) )
var (
// DefaultExcludes is the paths which are allowed by default
DefaultExcludes = []string{"/favicon.ico"}
)
// CombinedAuthHandler wraps a server and authenticates requests // CombinedAuthHandler wraps a server and authenticates requests
func CombinedAuthHandler(h http.Handler) http.Handler { func CombinedAuthHandler(h http.Handler) http.Handler {
return authHandler{ return authHandler{
@ -27,24 +22,19 @@ type authHandler struct {
auth auth.Auth auth auth.Auth
} }
const (
// BearerScheme is the prefix in the auth header
BearerScheme = "Bearer "
)
func (h authHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { func (h authHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// Extract the token from the request // Extract the token from the request
var token string var token string
if header := req.Header.Get("Authorization"); len(header) > 0 { if header := req.Header.Get("Authorization"); len(header) > 0 {
// Extract the auth token from the request // Extract the auth token from the request
if strings.HasPrefix(header, BearerScheme) { if strings.HasPrefix(header, auth.BearerScheme) {
token = header[len(BearerScheme):] token = header[len(auth.BearerScheme):]
} }
} else { } else {
// Get the token out the cookies if not provided in headers // Get the token out the cookies if not provided in headers
if c, err := req.Cookie("micro-token"); err == nil && c != nil { if c, err := req.Cookie("micro-token"); err == nil && c != nil {
token = strings.TrimPrefix(c.Value, auth.TokenCookieName+"=") token = strings.TrimPrefix(c.Value, auth.TokenCookieName+"=")
req.Header.Set("Authorization", BearerScheme+token) req.Header.Set("Authorization", auth.BearerScheme+token)
} }
} }

View File

@ -5,6 +5,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt"
"time" "time"
"github.com/micro/go-micro/v2/metadata" "github.com/micro/go-micro/v2/metadata"
@ -21,6 +22,8 @@ var (
ErrInvalidRole = errors.New("invalid role") ErrInvalidRole = errors.New("invalid role")
// ErrForbidden is returned when a user does not have the necessary roles to access a resource // ErrForbidden is returned when a user does not have the necessary roles to access a resource
ErrForbidden = errors.New("resource forbidden") ErrForbidden = errors.New("resource forbidden")
// BearerScheme used for Authorization header
BearerScheme = "Bearer "
) )
// Auth providers authentication and authorization // Auth providers authentication and authorization
@ -125,3 +128,8 @@ func ContextWithAccount(ctx context.Context, account *Account) (context.Context,
// generate a new context with the MetadataKey set // generate a new context with the MetadataKey set
return metadata.Set(ctx, MetadataKey, string(bytes)), nil return metadata.Set(ctx, MetadataKey, string(bytes)), nil
} }
// ContextWithToken sets the auth token in the context
func ContextWithToken(ctx context.Context, token string) (context.Context, error) {
return metadata.Set(ctx, "Authorization", fmt.Sprintf("%v%v", BearerScheme, token)), nil
}

View File

@ -11,6 +11,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/micro/go-micro/v2/auth"
"github.com/micro/go-micro/v2/broker" "github.com/micro/go-micro/v2/broker"
"github.com/micro/go-micro/v2/client" "github.com/micro/go-micro/v2/client"
"github.com/micro/go-micro/v2/client/selector" "github.com/micro/go-micro/v2/client/selector"
@ -26,10 +27,6 @@ import (
gmetadata "google.golang.org/grpc/metadata" gmetadata "google.golang.org/grpc/metadata"
) )
var (
BearerScheme = "Bearer "
)
type grpcClient struct { type grpcClient struct {
opts client.Options opts client.Options
pool *pool pool *pool
@ -137,7 +134,7 @@ func (g *grpcClient) call(ctx context.Context, node *registry.Node, req client.R
// set the authorization token if one is saved locally // set the authorization token if one is saved locally
if len(header["authorization"]) == 0 { if len(header["authorization"]) == 0 {
if token, err := config.Get("token"); err == nil && len(token) > 0 { if token, err := config.Get("token"); err == nil && len(token) > 0 {
header["authorization"] = BearerScheme + token header["authorization"] = auth.BearerScheme + token
} }
} }

View File

@ -31,7 +31,6 @@ type traceWrapper struct {
var ( var (
HeaderPrefix = "Micro-" HeaderPrefix = "Micro-"
BearerScheme = "Bearer "
) )
func (c *clientWrapper) setHeaders(ctx context.Context) context.Context { func (c *clientWrapper) setHeaders(ctx context.Context) context.Context {
@ -44,7 +43,7 @@ func (c *clientWrapper) setHeaders(ctx context.Context) context.Context {
tk := a.Options().Token tk := a.Options().Token
// if the token if exists and auth header isn't set then set it // if the token if exists and auth header isn't set then set it
if len(tk) > 0 && len(md["Authorization"]) == 0 { if len(tk) > 0 && len(md["Authorization"]) == 0 {
md["Authorization"] = BearerScheme + tk md["Authorization"] = auth.BearerScheme + tk
} }
} }
@ -174,11 +173,11 @@ func AuthHandler(fn func() auth.Auth, srvName string) server.HandlerWrapper {
var token string var token string
if header, ok := metadata.Get(ctx, "Authorization"); ok { if header, ok := metadata.Get(ctx, "Authorization"); ok {
// Ensure the correct scheme is being used // Ensure the correct scheme is being used
if !strings.HasPrefix(header, BearerScheme) { if !strings.HasPrefix(header, auth.BearerScheme) {
return errors.Unauthorized("go.micro.auth", "invalid authorization header. expected Bearer schema") return errors.Unauthorized("go.micro.auth", "invalid authorization header. expected Bearer schema")
} }
token = header[len(BearerScheme):] token = header[len(auth.BearerScheme):]
} }
// Inspect the token and get the account // Inspect the token and get the account