uaaclient

package module
v0.0.0-...-845e322 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 15, 2020 License: Apache-2.0 Imports: 14 Imported by: 0

README

uaaclient

UAA client provides receiving a token on behalf of the user.

Example middleware handle for authorizing a client in an application

// simple session list
var sessionList  = make(map[string]string)

// create new UAA client
UAAClient, _ = uaaclient.New(uaaclient.Config{
    ClientID:    "myapp",
    Host:        "localhost",
    Scheme:      "http",
    Secret:      "mysecret",
    RedirectURL: "/myapp/",
    UAAEndpoint: "/oauth",
})

func authorization(pass http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// search code in request
		if code, ok := uaaclient.GetCode(r); ok {
			// the code is exchanged for a token from the UAA server
			token, err := UAAClient.CodeToken(code)
			if err != nil {
				w.WriteHeader(http.StatusUnauthorized)
				return
			}

			// creating a new session and writing it to cookies
			sessionID := UAAClient.SetSessionCookie(w, r)

			sessionList[sessionID] = token

			pass(w, r)
			return

			// cookie session search
		} else if sessionID, err := uaaclient.GetSessionID(r); err == nil {

			if _, ok := sessionList[sessionID]; ok {
				pass(w, r)
				return
			}
		}

		// redirect of unauthorized users to the login page
		UAAClient.AuthRedirect(w, r, "")
	}
}

func handleApp(w http.ResponseWriter, r *http.Request) {
    // handle action
}

http.HandleFunc("/myapp/", authorization(handleApp))

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCode

func GetCode(r *http.Request) (string, bool)

GetCode searches for code in request query

func GetSessionID

func GetSessionID(r *http.Request) (string, error)

GetSessionID returns session ID from cookie

Types

type Client

type Client struct {
	// Client identifier, unique within identity zone.
	// Required
	ClientID string `json:"client_id"`

	// List of grant types that can be used to obtain a token with this client.
	// Can include authorization_code, password, implicit, and/or client_credntials.
	// Optional
	AuthorizedGrantTypes []string `json:"authorized_grant_types,omitempty"`

	// Allowed URI pattern for redirect during authorization.
	// Wildcard patterns can be specified using the Ant-style pattern.
	// Null/Empty value is forbidden.
	// Optional
	RedirectURI []string `json:"redirect_uri,omitempty"`

	// Scopes allowed for the client.
	// Optional (defaults to "uaa.none")
	Scope []string `json:"scope,omitempty"`

	// Resources the client is allowed access to
	// Optional (defaults to [])
	ResourceIds []string `json:"resource_ids,omitempty"`

	// Scopes which the client is able to grant when creating a client.
	// Optional (defaults to "uaa.none")
	Authorities []string `json:"authorities,omitempty"`

	// Scopes that do not require user approval.
	// Optional (defaults to [])
	Autoapprove interface{} `json:"autoapprove,omitempty"`

	// Time in seconds to access token expiration after it is issued
	// Optional
	AccessTokenValidity uint32 `json:"access_token_validity,omitempty"`

	// time in seconds to refresh token expiration after it is issued
	// Optional
	RefreshTokenValidity uint32 `json:"refresh_token_validity,omitempty"`

	// 	A list of origin keys (alias) for identity providers the client
	// is limited to. Null implies any identity provider is allowed.
	// Optional
	Allowedproviders []string `json:"allowedproviders,omitempty"`

	// A human readable name for the client
	// Optional
	Name string `json:"name,omitempty"`

	// A random string used to generate the client's revokation key.
	// Change this value to revoke all active tokens for the client.
	// Optional
	TokenSalt string `json:"token_salt,omitempty"`

	// What scope the bearer token had when client was created
	// Optional
	CreatedWith string `json:"createdwith,omitempty"`

	// A list of group names. If a user doesn't belong to all the required
	// groups, the user will not be authenticated and no tokens will be issued
	// to this client for that user. If this field is not set, authentication
	// and token issuance will proceed normally.
	// Optional
	RequiredUserGroups []string `json:"required_user_groups,omitempty"`

	// A secret string used for authenticating as this client. To support
	// secret rotation this can be space delimited string of two secrets.
	// Required if the client allows authorization_code or client_credentials
	// grant type
	ClientSecret string `json:"client_secret,omitempty"`
	// contains filtered or unexported fields
}

Client ...

func (*Client) GetExtra

func (c *Client) GetExtra(key string) (interface{}, bool)

GetExtra ...

func (*Client) MarshalJSON

func (c *Client) MarshalJSON() ([]byte, error)

MarshalJSON ...

func (*Client) SetExtra

func (c *Client) SetExtra(key string, value interface{})

SetExtra ...

func (*Client) UnmarshalJSON

func (c *Client) UnmarshalJSON(b []byte) error

UnmarshalJSON ...

type Clients

type Clients struct {
	// contains filtered or unexported fields
}

Clients ...

func (*Clients) Create

func (c *Clients) Create(t *Token, client *Client) (bool, error)

Create ...

func (*Clients) Delete

func (c *Clients) Delete(t *Token, clientID string) (int, error)

Delete ...

func (*Clients) Get

func (c *Clients) Get(t *Token, clientID string) (*Client, error)

Get ...

type Config

type Config struct {
	// ClientID is the application's ID.
	ClientID string
	// ClientSecret is the application's secret.
	Secret string
	// http or https
	Scheme string
	// Host is the UAA host
	Host string
	// UAAEndpoint is the UAA endpoint that is obtained from hitting
	UAAEndpoint string
	// RedirectURL is the URL to redirect users going through
	// the OAuth flow, after the resource owner's URLs.
	RedirectURL string

	Scopes []string

	Context context.Context
}

Config for UaaClient

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig ...

type Payload

type Payload struct {
	// JWT ID. unique identifier for this token
	Jti string `json:"jti"`
	// JWT Time the token was issued (epoch)
	IatRaw int64 `json:"iat"`
	Iat    time.Time
	// JWT Time the token expires (epoch)
	ExpRaw int64 `json:"exp"`
	Exp    time.Time
	// JWT Issuer (who created and signed this token)
	Iss string `json:"iss"`
	// UAA Used in multi-tenant environments to identity the tenant
	Zid string `json:"zid"`
	// UAA Identity provider that authenticated the end-user
	Origin string `json:"origin"`
	// UAA Canonical username of the end-user
	UserName string `json:"user_name"`
	// OIDC Email address of the end-user
	Email string `json:"email"`
	// OIDC Subject (who the token refers to)
	Sub string `json:"sub"`
	// OAuth List of scopes (group memberships) this access token has
	Scope []string `json:"scope"`
	//
	Authorities []string `json:"authorities"`
	// OAuth Client ID that requested the token
	ClientID string `json:"client_id"`
	// OAuth Type of authorization grant
	GrantType string `json:"grant_type"`
}

Payload ...

type Session

type Session struct {
	ID     string
	Cookie http.Cookie
}

Session ...

type Token

type Token struct {
	oauth2.Token
	Payload Payload
}

Token ...

func TokenFromHeader

func TokenFromHeader(r *http.Request) (*Token, bool, error)

TokenFromHeader searches for Token in the request header. Tries to deserialize JWT to get an expiration date.

func (*Token) UnsafeParsePayload

func (t *Token) UnsafeParsePayload() error

UnsafeParsePayload deserializes JWT and saves the result in Payload. For signed JWTs, the claims are not verified. This function won't work for encrypted JWTs.

type UaaClient

type UaaClient struct {
	// contains filtered or unexported fields
}

UaaClient ...

func New

func New(cfg Config) (*UaaClient, error)

New ...

func (*UaaClient) AuthRedirect

func (u *UaaClient) AuthRedirect(w http.ResponseWriter, r *http.Request, state string, opts ...oauth2.AuthCodeOption)

AuthRedirect ...

func (*UaaClient) Clients

func (u *UaaClient) Clients() *Clients

Clients ...

func (*UaaClient) CodeToken

func (u *UaaClient) CodeToken(code string, opts ...oauth2.AuthCodeOption) (*Token, error)

CodeToken ...

func (*UaaClient) PasswordCredentialsToken

func (u *UaaClient) PasswordCredentialsToken(username, password string) (*Token, error)

PasswordCredentialsToken ...

func (*UaaClient) SetBaseAuth

func (u *UaaClient) SetBaseAuth(r *http.Request)

SetBaseAuth ...

func (*UaaClient) SetSessionCookie

func (o *UaaClient) SetSessionCookie(w http.ResponseWriter, r *http.Request) string

SetSessionCookie creates a new session and writes it in a cookie.

func (*UaaClient) ValidToken

func (u *UaaClient) ValidToken(t *Token) error

ValidToken ...

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL