forked from bitly/oauth2_proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
azure.go
124 lines (102 loc) · 2.45 KB
/
azure.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package providers
import (
"errors"
"fmt"
"github.com/bitly/oauth2_proxy/api"
"log"
"net/http"
"net/url"
"github.com/bitly/go-simplejson"
)
type AzureProvider struct {
*ProviderData
Tenant string
}
func NewAzureProvider(p *ProviderData) *AzureProvider {
p.ProviderName = "Azure"
if p.ProfileURL == nil || p.ProfileURL.String() == "" {
p.ProfileURL = &url.URL{
Scheme: "https",
Host: "graph.windows.net",
Path: "/me",
RawQuery: "api-version=1.6",
}
}
if p.ProtectedResource == nil || p.ProtectedResource.String() == "" {
p.ProtectedResource = &url.URL{
Scheme: "https",
Host: "graph.windows.net",
}
}
if p.Scope == "" {
p.Scope = "openid"
}
return &AzureProvider{ProviderData: p}
}
func (p *AzureProvider) Configure(tenant string) {
p.Tenant = tenant
if tenant == "" {
p.Tenant = "common"
}
if p.LoginURL == nil || p.LoginURL.String() == "" {
p.LoginURL = &url.URL{
Scheme: "https",
Host: "login.microsoftonline.com",
Path: "/" + p.Tenant + "/oauth2/authorize"}
}
if p.RedeemURL == nil || p.RedeemURL.String() == "" {
p.RedeemURL = &url.URL{
Scheme: "https",
Host: "login.microsoftonline.com",
Path: "/" + p.Tenant + "/oauth2/token",
}
}
}
func getAzureHeader(access_token string) http.Header {
header := make(http.Header)
header.Set("Authorization", fmt.Sprintf("Bearer %s", access_token))
return header
}
func getEmailFromJSON(json *simplejson.Json) (string, error) {
var email string
var err error
email, err = json.Get("mail").String()
if err != nil || email == "" {
otherMails, otherMailsErr := json.Get("otherMails").Array()
if len(otherMails) > 0{
email = otherMails[0].(string)
}
err = otherMailsErr
}
return email, err
}
func (p *AzureProvider) GetEmailAddress(s *SessionState) (string, error) {
var email string
var err error
if s.AccessToken == "" {
return "", errors.New("missing access token")
}
req, err := http.NewRequest("GET", p.ProfileURL.String(), nil)
if err != nil {
return "", err
}
req.Header = getAzureHeader(s.AccessToken)
json, err := api.Request(req)
if err != nil {
return "", err
}
email, err = getEmailFromJSON(json)
if err == nil && email != "" {
return email, err
}
email, err = json.Get("userPrincipalName").String()
if err != nil {
log.Printf("failed making request %s", err)
return "", err
}
if email == "" {
log.Printf("failed to get email address")
return "", err
}
return email, err
}