adal

package
v8.4.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2017 License: Apache-2.0 Imports: 17 Imported by: 0

README

Azure Active Directory library for Go

This project provides a stand alone Azure Active Directory library for Go. The code was extracted from go-autorest project, which is used as a base for azure-sdk-for-go.

Installation

go get -u github.com/Azure/go-autorest/autorest/adal

Usage

An Active Directory application is required in order to use this library. An application can be registered in the Azure Portal follow these guidelines or using the Azure CLI.

Register an Azure AD Application with secret
  1. Register a new application with a secret credential

    az ad app create \
       --display-name example-app \
       --homepage https://example-app/home \
       --identifier-uris https://example-app/app \
       --password secret
    
  2. Create a service principal using the Application ID from previous step

    az ad sp create --id "Application ID"
    
    • Replace Application ID with appId from step 1.
Register an Azure AD Application with certificate
  1. Create a private key

    openssl genrsa -out "example-app.key" 2048
    
  2. Create the certificate

    openssl req -new -key "example-app.key" -subj "/CN=example-app" -out "example-app.csr"
    openssl x509 -req -in "example-app.csr" -signkey "example-app.key" -out "example-app.crt" -days 10000
    
  3. Create the PKCS12 version of the certificate containing also the private key

    openssl pkcs12 -export -out "example-app.pfx" -inkey "example-app.key" -in "example-app.crt" -passout pass:
    
    
  4. Register a new application with the certificate content form example-app.crt

    certificateContents="$(tail -n+2 "example-app.crt" | head -n-1)"
    
    az ad app create \
       --display-name example-app \
       --homepage https://example-app/home \
       --identifier-uris https://example-app/app \
       --key-usage Verify --end-date 2018-01-01 \
       --key-value "${certificateContents}"
    
  5. Create a service principal using the Application ID from previous step

    az ad sp create --id "APPLICATION_ID"
    
    • Replace APPLICATION_ID with appId from step 4.
Grant the necessary permissions

Azure relies on a Role-Based Access Control (RBAC) model to manage the access to resources at a fine-grained level. There is a set of pre-defined roles which can be assigned to a service principal of an Azure AD application depending of your needs.

az role assignment create --assigner "SERVICE_PRINCIPAL_ID" --role "ROLE_NAME"
  • Replace the SERVICE_PRINCIPAL_ID with the appId from previous step.
  • Replace the ROLE_NAME with a role name of your choice.

It is also possible to define custom role definitions.

az role definition create --role-definition role-definition.json
  • Check custom roles for more details regarding the content of role-definition.json file.
Acquire Access Token

The common configuration used by all flows:

const activeDirectoryEndpoint = "https://login.microsoftonline.com/"
tenantID := "TENANT_ID"
oauthConfig, err := adal.NewOAuthConfig(activeDirectoryEndpoint, tenantID)

applicationID := "APPLICATION_ID"

callback := func(token adal.Token) error {
    // This is called after the token is acquired
}

// The resource for which the token is acquired
resource := "https://management.core.windows.net/"
  • Replace the TENANT_ID with your tenant ID.
  • Replace the APPLICATION_ID with the value from previous section.
Client Credentials
applicationSecret := "APPLICATION_SECRET"

spt, err := adal.NewServicePrincipalToken(
	oauthConfig,
	appliationID,
	applicationSecret,
	resource,
	callbacks...)
if err != nil {
	return nil, err
}

// Acquire a new access token
err  = spt.Refresh()
if (err == nil) {
    token := spt.Token
}
  • Replace the APPLICATION_SECRET with the password value from previous section.
Client Certificate
certificatePath := "./example-app.pfx"

certData, err := ioutil.ReadFile(certificatePath)
if err != nil {
	return nil, fmt.Errorf("failed to read the certificate file (%s): %v", certificatePath, err)
}

// Get the certificate and private key from pfx file
certificate, rsaPrivateKey, err := decodePkcs12(certData, "")
if err != nil {
	return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err)
}

spt, err := adal.NewServicePrincipalTokenFromCertificate(
	oauthConfig,
	applicationID,
	certificate,
	rsaPrivateKey,
	resource,
	callbacks...)

// Acquire a new access token
err  = spt.Refresh()
if (err == nil) {
    token := spt.Token
}
  • Update the certificate path to point to the example-app.pfx file which was created in previous section.
Device Code
oauthClient := &http.Client{}

// Acquire the device code
deviceCode, err := adal.InitiateDeviceAuth(
	oauthClient,
	oauthConfig,
	applicationID,
	resource)
if err != nil {
	return nil, fmt.Errorf("Failed to start device auth flow: %s", err)
}

// Display the authentication message
fmt.Println(*deviceCode.Message)

// Wait here until the user is authenticated
token, err := adal.WaitForUserCompletion(oauthClient, deviceCode)
if err != nil {
	return nil, fmt.Errorf("Failed to finish device auth flow: %s", err)
}

spt, err := adal.NewServicePrincipalTokenFromManualToken(
	oauthConfig,
	applicationID,
	resource,
	*token,
	callbacks...)

if (err == nil) {
    token := spt.Token
}
Command Line Tool

A command line tool is available in cmd/adal.go that can acquire a token for a given resource. It supports all flows mentioned above.

adal -h

Usage of ./adal:
  -applicationId string
        application id
  -certificatePath string
        path to pk12/PFC application certificate
  -mode string
        authentication mode (device, secret, cert, refresh) (default "device")
  -resource string
        resource for which the token is requested
  -secret string
        application secret
  -tenantId string
        tenant id
  -tokenCachePath string
        location of oath token cache (default "/home/cgc/.adal/accessToken.json")

Example acquire a token for https://management.core.windows.net/ using device code flow:

adal -mode device \
    -applicationId "APPLICATION_ID" \
    -tenantId "TENANT_ID" \
    -resource https://management.core.windows.net/

Documentation

Index

Constants

View Source
const (

	// OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow
	OAuthGrantTypeDeviceCode = "device_code"

	// OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows
	OAuthGrantTypeClientCredentials = "client_credentials"

	// OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows
	OAuthGrantTypeRefreshToken = "refresh_token"
)

Variables

View Source
var (
	// ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow
	ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix)

	// ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow
	ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix)

	// ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow
	ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix)

	// ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow
	ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix)

	// ErrDeviceSlowDown represents the service telling us we're polling too often during device flow
	ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix)

	// ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow
	ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix)

	// ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow
	ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", logPrefix)
)

Functions

func GetMSIVMEndpoint

func GetMSIVMEndpoint() (string, error)

GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines.

func SaveToken

func SaveToken(path string, mode os.FileMode, token Token) error

SaveToken persists an oauth token at the given location on disk. It moves the new file into place so it can safely be used to replace an existing file that maybe accessed by multiple processes.

Types

type DeviceCode

type DeviceCode struct {
	DeviceCode      *string `json:"device_code,omitempty"`
	UserCode        *string `json:"user_code,omitempty"`
	VerificationURL *string `json:"verification_url,omitempty"`
	ExpiresIn       *int64  `json:"expires_in,string,omitempty"`
	Interval        *int64  `json:"interval,string,omitempty"`

	Message     *string `json:"message"` // Azure specific
	Resource    string  // store the following, stored when initiating, used when exchanging
	OAuthConfig OAuthConfig
	ClientID    string
}

DeviceCode is the object returned by the device auth endpoint It contains information to instruct the user to complete the auth flow

func InitiateDeviceAuth

func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error)

InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode that can be used with CheckForUserCompletion or WaitForUserCompletion.

type OAuthConfig

type OAuthConfig struct {
	AuthorityEndpoint  url.URL
	AuthorizeEndpoint  url.URL
	TokenEndpoint      url.URL
	DeviceCodeEndpoint url.URL
}

OAuthConfig represents the endpoints needed in OAuth operations

func NewOAuthConfig

func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error)

NewOAuthConfig returns an OAuthConfig with tenant specific urls

type OAuthTokenProvider

type OAuthTokenProvider interface {
	OAuthToken() string
}

OAuthTokenProvider is an interface which should be implemented by an access token retriever

type Refresher

type Refresher interface {
	Refresh() error
	RefreshExchange(resource string) error
	EnsureFresh() error
}

Refresher is an interface for token refresh functionality

type SendDecorator

type SendDecorator func(Sender) Sender

SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the http.Request and pass it along or, first, pass the http.Request along then react to the http.Response result.

type Sender

type Sender interface {
	Do(*http.Request) (*http.Response, error)
}

Sender is the interface that wraps the Do method to send HTTP requests.

The standard http.Client conforms to this interface.

func CreateSender

func CreateSender(decorators ...SendDecorator) Sender

CreateSender creates, decorates, and returns, as a Sender, the default http.Client.

func DecorateSender

func DecorateSender(s Sender, decorators ...SendDecorator) Sender

DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to the Sender. Decorators are applied in the order received, but their affect upon the request depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a post-decorator (pass the http.Request along and react to the results in http.Response).

type SenderFunc

type SenderFunc func(*http.Request) (*http.Response, error)

SenderFunc is a method that implements the Sender interface.

func (SenderFunc) Do

func (sf SenderFunc) Do(r *http.Request) (*http.Response, error)

Do implements the Sender interface on SenderFunc.

type ServicePrincipalCertificateSecret

type ServicePrincipalCertificateSecret struct {
	Certificate *x509.Certificate
	PrivateKey  *rsa.PrivateKey
}

ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs.

func (*ServicePrincipalCertificateSecret) SetAuthenticationValues

func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret. It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate.

func (*ServicePrincipalCertificateSecret) SignJwt

SignJwt returns the JWT signed with the certificate's private key.

type ServicePrincipalMSISecret

type ServicePrincipalMSISecret struct {
}

ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension.

func (*ServicePrincipalMSISecret) SetAuthenticationValues

func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret.

type ServicePrincipalNoSecret

type ServicePrincipalNoSecret struct {
}

ServicePrincipalNoSecret represents a secret type that contains no secret meaning it is not valid for fetching a fresh token. This is used by Manual

func (*ServicePrincipalNoSecret) SetAuthenticationValues

func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret It only returns an error for the ServicePrincipalNoSecret type

type ServicePrincipalSecret

type ServicePrincipalSecret interface {
	SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error
}

ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form that is submitted when acquiring an oAuth token.

type ServicePrincipalToken

type ServicePrincipalToken struct {
	Token
	// contains filtered or unexported fields
}

ServicePrincipalToken encapsulates a Token created for a Service Principal.

func NewServicePrincipalToken

func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal credentials scoped to the named resource.

func NewServicePrincipalTokenFromCertificate

func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromCertificate create a ServicePrincipalToken from the supplied pkcs12 bytes.

func NewServicePrincipalTokenFromMSI

func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension.

func NewServicePrincipalTokenFromManualToken

func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token

func NewServicePrincipalTokenWithSecret

func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error)

NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation.

func (*ServicePrincipalToken) EnsureFresh

func (spt *ServicePrincipalToken) EnsureFresh() error

EnsureFresh will refresh the token if it will expire within the refresh window (as set by RefreshWithin) and autoRefresh flag is on.

func (*ServicePrincipalToken) InvokeRefreshCallbacks

func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error

InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization

func (*ServicePrincipalToken) Refresh

func (spt *ServicePrincipalToken) Refresh() error

Refresh obtains a fresh token for the Service Principal.

func (*ServicePrincipalToken) RefreshExchange

func (spt *ServicePrincipalToken) RefreshExchange(resource string) error

RefreshExchange refreshes the token, but for a different resource.

func (*ServicePrincipalToken) SetAutoRefresh

func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool)

SetAutoRefresh enables or disables automatic refreshing of stale tokens.

func (*ServicePrincipalToken) SetRefreshWithin

func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration)

SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will refresh the token.

func (*ServicePrincipalToken) SetSender

func (spt *ServicePrincipalToken) SetSender(s Sender)

SetSender sets the http.Client used when obtaining the Service Principal token. An undecorated http.Client is used by default.

type ServicePrincipalTokenSecret

type ServicePrincipalTokenSecret struct {
	ClientSecret string
}

ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization.

func (*ServicePrincipalTokenSecret) SetAuthenticationValues

func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error

SetAuthenticationValues is a method of the interface ServicePrincipalSecret. It will populate the form submitted during oAuth Token Acquisition using the client_secret.

type Token

type Token struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`

	ExpiresIn string `json:"expires_in"`
	ExpiresOn string `json:"expires_on"`
	NotBefore string `json:"not_before"`

	Resource string `json:"resource"`
	Type     string `json:"token_type"`
}

Token encapsulates the access token used to authorize Azure requests.

func CheckForUserCompletion

func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error)

CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint to see if the device flow has: been completed, timed out, or otherwise failed

func LoadToken

func LoadToken(path string) (*Token, error)

LoadToken restores a Token object from a file located at 'path'.

func WaitForUserCompletion

func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error)

WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'.

func (Token) Expires

func (t Token) Expires() time.Time

Expires returns the time.Time when the Token expires.

func (Token) IsExpired

func (t Token) IsExpired() bool

IsExpired returns true if the Token is expired, false otherwise.

func (*Token) OAuthToken

func (t *Token) OAuthToken() string

OAuthToken return the current access token

func (Token) WillExpireIn

func (t Token) WillExpireIn(d time.Duration) bool

WillExpireIn returns true if the Token will expire after the passed time.Duration interval from now, false otherwise.

type TokenError

type TokenError struct {
	Error            *string `json:"error,omitempty"`
	ErrorCodes       []int   `json:"error_codes,omitempty"`
	ErrorDescription *string `json:"error_description,omitempty"`
	Timestamp        *string `json:"timestamp,omitempty"`
	TraceID          *string `json:"trace_id,omitempty"`
}

TokenError is the object returned by the token exchange endpoint when something is amiss

type TokenRefreshCallback

type TokenRefreshCallback func(Token) error

TokenRefreshCallback is the type representing callbacks that will be called after a successful token refresh

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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