/
azureadb2c.go
201 lines (173 loc) · 5.12 KB
/
azureadb2c.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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package sso
import (
"context"
"fmt"
"github.com/authgear/authgear-server/pkg/lib/authn/stdattrs"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/util/clock"
)
type Azureadb2cImpl struct {
Clock clock.Clock
ProviderConfig config.OAuthSSOProviderConfig
Credentials config.OAuthSSOProviderCredentialsItem
StandardAttributesNormalizer StandardAttributesNormalizer
HTTPClient OAuthHTTPClient
}
func (f *Azureadb2cImpl) getOpenIDConfiguration() (*OIDCDiscoveryDocument, error) {
tenant := f.ProviderConfig.Tenant
policy := f.ProviderConfig.Policy
endpoint := fmt.Sprintf(
"https://%s.b2clogin.com/%s.onmicrosoft.com/%s/v2.0/.well-known/openid-configuration",
tenant,
tenant,
policy,
)
return FetchOIDCDiscoveryDocument(f.HTTPClient, endpoint)
}
func (f *Azureadb2cImpl) Type() config.OAuthSSOProviderType {
return config.OAuthSSOProviderTypeAzureADB2C
}
func (f *Azureadb2cImpl) Config() config.OAuthSSOProviderConfig {
return f.ProviderConfig
}
func (f *Azureadb2cImpl) GetAuthURL(param GetAuthURLParam) (string, error) {
c, err := f.getOpenIDConfiguration()
if err != nil {
return "", err
}
return c.MakeOAuthURL(AuthorizationURLParams{
ClientID: f.ProviderConfig.ClientID,
RedirectURI: param.RedirectURI,
Scope: f.ProviderConfig.Type.Scope(),
ResponseType: ResponseTypeCode,
ResponseMode: param.ResponseMode,
State: param.State,
Prompt: f.GetPrompt(param.Prompt),
Nonce: param.Nonce,
}), nil
}
func (f *Azureadb2cImpl) GetAuthInfo(r OAuthAuthorizationResponse, param GetAuthInfoParam) (authInfo AuthInfo, err error) {
return f.OpenIDConnectGetAuthInfo(r, param)
}
func (f *Azureadb2cImpl) OpenIDConnectGetAuthInfo(r OAuthAuthorizationResponse, param GetAuthInfoParam) (authInfo AuthInfo, err error) {
c, err := f.getOpenIDConfiguration()
if err != nil {
return
}
// OPTIMIZE(sso): Cache JWKs
keySet, err := c.FetchJWKs(f.HTTPClient)
if err != nil {
return
}
var tokenResp AccessTokenResp
jwtToken, err := c.ExchangeCode(
f.HTTPClient,
f.Clock,
r.Code,
keySet,
f.ProviderConfig.ClientID,
f.Credentials.ClientSecret,
param.RedirectURI,
param.Nonce,
&tokenResp,
)
if err != nil {
return
}
claims, err := jwtToken.AsMap(context.TODO())
if err != nil {
return
}
iss, ok := claims["iss"].(string)
if !ok {
err = OAuthProtocolError.New("iss not found in ID token")
return
}
if iss != c.Issuer {
err = OAuthProtocolError.New(
fmt.Sprintf("iss: %v != %v", iss, c.Issuer),
)
return
}
sub, ok := claims["sub"].(string)
if !ok || sub == "" {
err = OAuthProtocolError.New("sub not found in ID Token")
return
}
authInfo.ProviderRawProfile = claims
authInfo.ProviderUserID = sub
stdAttrs, err := f.Extract(claims)
if err != nil {
return
}
authInfo.StandardAttributes = stdAttrs
err = f.StandardAttributesNormalizer.Normalize(authInfo.StandardAttributes)
if err != nil {
return
}
return
}
func (f *Azureadb2cImpl) Extract(claims map[string]interface{}) (stdattrs.T, error) {
// Here is the list of possible builtin claims of user flows
// https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-flow-overview#user-flows
// city: free text
// country: free text
// jobTitle: free text
// legalAgeGroupClassification: a enum with undocumented variants
// postalCode: free text
// state: free text
// streetAddress: free text
// newUser: true means the user signed up newly
// oid: sub is identical to it by default.
// emails: if non-empty, the first value corresponds to standard claim
// name: correspond to standard claim
// given_name: correspond to standard claim
// family_name: correspond to standard claim
// For custom policy we further recognize the following claims.
// https://learn.microsoft.com/en-us/azure/active-directory-b2c/user-profile-attributes
// signInNames.emailAddress: string
extractString := func(input map[string]interface{}, output stdattrs.T, key string) {
if value, ok := input[key].(string); ok && value != "" {
output[key] = value
}
}
out := stdattrs.T{}
extractString(claims, out, stdattrs.Name)
extractString(claims, out, stdattrs.GivenName)
extractString(claims, out, stdattrs.FamilyName)
var email string
if email == "" {
if ifaceSlice, ok := claims["emails"].([]interface{}); ok {
for _, iface := range ifaceSlice {
if str, ok := iface.(string); ok && str != "" {
email = str
}
}
}
}
if email == "" {
if str, ok := claims["signInNames.emailAddress"].(string); ok {
if str != "" {
email = str
}
}
}
out[stdattrs.Email] = email
return stdattrs.Extract(out, stdattrs.ExtractOptions{
EmailRequired: *f.ProviderConfig.Claims.Email.Required,
})
}
func (f *Azureadb2cImpl) GetPrompt(prompt []string) []string {
// The only supported value is login.
// See https://docs.microsoft.com/en-us/azure/active-directory-b2c/openid-connect
for _, p := range prompt {
if p == "login" {
return []string{"login"}
}
}
return []string{}
}
var (
_ OAuthProvider = &Azureadb2cImpl{}
_ OpenIDConnectProvider = &Azureadb2cImpl{}
)