3 // Copyright 2017 Microsoft Corporation
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
9 // http://www.apache.org/licenses/LICENSE-2.0
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
22 // OAuthConfig represents the endpoints needed
23 // in OAuth operations
24 type OAuthConfig struct {
25 AuthorityEndpoint url.URL `json:"authorityEndpoint"`
26 AuthorizeEndpoint url.URL `json:"authorizeEndpoint"`
27 TokenEndpoint url.URL `json:"tokenEndpoint"`
28 DeviceCodeEndpoint url.URL `json:"deviceCodeEndpoint"`
31 // IsZero returns true if the OAuthConfig object is zero-initialized.
32 func (oac OAuthConfig) IsZero() bool {
33 return oac == OAuthConfig{}
36 func validateStringParam(param, name string) error {
38 return fmt.Errorf("parameter '" + name + "' cannot be empty")
43 // NewOAuthConfig returns an OAuthConfig with tenant specific urls
44 func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) {
46 return NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID, &apiVer)
49 // NewOAuthConfigWithAPIVersion returns an OAuthConfig with tenant specific urls.
50 // If apiVersion is not nil the "api-version" query parameter will be appended to the endpoint URLs with the specified value.
51 func NewOAuthConfigWithAPIVersion(activeDirectoryEndpoint, tenantID string, apiVersion *string) (*OAuthConfig, error) {
52 if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil {
56 // it's legal for tenantID to be empty so don't validate it
57 if apiVersion != nil {
58 if err := validateStringParam(*apiVersion, "apiVersion"); err != nil {
61 api = fmt.Sprintf("?api-version=%s", *apiVersion)
63 const activeDirectoryEndpointTemplate = "%s/oauth2/%s%s"
64 u, err := url.Parse(activeDirectoryEndpoint)
68 authorityURL, err := u.Parse(tenantID)
72 authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", api))
76 tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", api))
80 deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", api))
86 AuthorityEndpoint: *authorityURL,
87 AuthorizeEndpoint: *authorizeURL,
88 TokenEndpoint: *tokenURL,
89 DeviceCodeEndpoint: *deviceCodeURL,