/
OpenIdOAuthProvider.cs
289 lines (233 loc) · 13.1 KB
/
OpenIdOAuthProvider.cs
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
using System;
using System.Collections.Generic;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.Configuration;
using ServiceStack.ServiceClient.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.Text;
namespace ServiceStack.Authentication.OpenId
{
public class OpenIdOAuthProvider : OAuthProvider
{
public const string DefaultName = "OpenId";
public OpenIdOAuthProvider(IResourceManager appSettings, string name = DefaultName, string realm = null)
: base(appSettings, realm, name) { }
public virtual ClaimsRequest CreateClaimsRequest(IHttpRequest httpReq)
{
return new ClaimsRequest {
Country = DemandLevel.Request,
Email = DemandLevel.Request,
Gender = DemandLevel.Require,
PostalCode = DemandLevel.Require,
TimeZone = DemandLevel.Require,
};
}
public override object Authenticate(IServiceBase authService, IAuthSession session, Auth request)
{
var tokens = Init(authService, ref session, request);
var httpReq = authService.RequestContext.Get<IHttpRequest>();
var httpMethod = httpReq.HttpMethod;
if (httpMethod == HttpMethod.Post)
{
var openIdUrl = httpReq.GetParam("OpenIdUrl") ?? base.AuthRealm;
if (openIdUrl.IsNullOrEmpty())
throw new ArgumentNullException("'OpenIdUrl' is required a required field");
try
{
using (var openid = new OpenIdRelyingParty())
{
var openIdRequest = openid.CreateRequest(openIdUrl);
AddAttributeExchangeExtensions(openIdRequest);
// This is where you would add any OpenID extensions you wanted
// to include in the authentication request.
openIdRequest.AddExtension(CreateClaimsRequest(httpReq));
// Send your visitor to their Provider for authentication.
var openIdResponse = openIdRequest.RedirectingResponse;
var contentType = openIdResponse.Headers[HttpHeaders.ContentType];
var httpResult = new HttpResult(openIdResponse.ResponseStream, contentType) {
StatusCode = openIdResponse.Status,
StatusDescription = "Moved Temporarily",
};
foreach (string header in openIdResponse.Headers)
{
httpResult.Headers[header] = openIdResponse.Headers[header];
}
return httpResult;
}
}
catch (ProtocolException ex)
{
Log.Error("Falied to login to {0}".Fmt(openIdUrl), ex);
return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
}
}
if (httpMethod == HttpMethod.Get)
{
using (var openid = new OpenIdRelyingParty())
{
var response = openid.GetResponse();
if (response != null)
{
switch (response.Status)
{
case AuthenticationStatus.Authenticated:
// This is where you would look for any OpenID extension responses included
// in the authentication assertion.
var claimsResponse = response.GetExtension<ClaimsResponse>();
var authInfo = claimsResponse.ToDictionary();
authInfo["user_id"] = response.ClaimedIdentifier; //a url
// Store off the "friendly" username to display -- NOT for username lookup
authInfo["openid_ref"] = response.FriendlyIdentifierForDisplay;
var provided = GetAttributeEx(response);
foreach (var entry in provided)
{
authInfo[entry.Key] = entry.Value;
}
// Use FormsAuthentication to tell ASP.NET that the user is now logged in,
// with the OpenID Claimed Identifier as their username.
session.IsAuthenticated = true;
authService.SaveSession(session, SessionExpiry);
OnAuthenticated(authService, session, tokens, authInfo);
//Haz access!
return authService.Redirect(session.ReferrerUrl.AddHashParam("s", "1"));
case AuthenticationStatus.Canceled:
return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "ProviderCancelled"));
case AuthenticationStatus.Failed:
return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
}
}
}
}
//Shouldn't get here
return authService.Redirect(session.ReferrerUrl.AddHashParam("f", "Unknown"));
}
protected override void LoadUserAuthInfo(AuthUserSession userSession, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
if (authInfo.ContainsKey("user_id"))
tokens.UserId = authInfo.GetValueOrDefault("user_id");
if (authInfo.ContainsKey("name"))
tokens.DisplayName = authInfo.GetValueOrDefault("name");
if (authInfo.ContainsKey("FullName"))
{
tokens.FullName = authInfo.GetValueOrDefault("FullName");
if (tokens.DisplayName.IsNullOrEmpty())
tokens.DisplayName = tokens.FullName;
}
if (authInfo.ContainsKey("Email"))
tokens.Email = authInfo.GetValueOrDefault("Email");
if (authInfo.ContainsKey("BirthDate"))
tokens.BirthDate = authInfo.GetValueOrDefault("BirthDate").FromJsv<DateTime?>();
if (authInfo.ContainsKey("BirthDateRaw"))
tokens.BirthDateRaw = authInfo.GetValueOrDefault("BirthDateRaw");
if (authInfo.ContainsKey("Country"))
tokens.Country = authInfo.GetValueOrDefault("Country");
if (authInfo.ContainsKey("Culture"))
tokens.Culture = authInfo.GetValueOrDefault("Culture");
if (authInfo.ContainsKey("Gender"))
tokens.Gender = authInfo.GetValueOrDefault("Gender");
if (authInfo.ContainsKey("MailAddress"))
tokens.MailAddress = authInfo.GetValueOrDefault("MailAddress");
if (authInfo.ContainsKey("Nickname"))
tokens.Nickname = authInfo.GetValueOrDefault("Nickname");
if (authInfo.ContainsKey("PostalCode"))
tokens.PostalCode = authInfo.GetValueOrDefault("PostalCode");
if (authInfo.ContainsKey("TimeZone"))
tokens.TimeZone = authInfo.GetValueOrDefault("TimeZone");
LoadUserOAuthProvider(userSession, tokens);
}
public override void LoadUserOAuthProvider(IAuthSession authSession, IOAuthTokens tokens)
{
var userSession = authSession as AuthUserSession;
if (userSession == null) return;
}
private void AddAttributeExchangeExtensions(IAuthenticationRequest auth)
{
// Try to use OpenId 2.0's attribute exchange
var fetch = new FetchRequest();
//Technically, http://axschema.org/... are "standard", but we'll still find these in the wild
fetch.Attributes.Add(new AttributeRequest("http://schema.openid.net/namePerson", false));
fetch.Attributes.Add(new AttributeRequest("http://schema.openid.net/contact/email", false));
fetch.Attributes.AddRequired("http://axschema.org/contact/country/home");
fetch.Attributes.AddRequired("http://axschema.org/namePerson/first");
fetch.Attributes.AddRequired("http://axschema.org/namePerson/last");
fetch.Attributes.AddRequired("http://axschema.org/pref/language");
fetch.Attributes.AddRequired("http://schemas.openid.net/ax/api/user_id");
//Standard compliant AX schema
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName, false));
//For... no good reason, really, google OpenId requires you "require" an e-mail address to get it
bool requireEmail = auth.Provider.Uri.AbsoluteUri.Contains(".google.com");
fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, requireEmail));
auth.AddExtension(fetch);
}
/// <summary>
/// Extracts an Attribute Exchange response, if one exists
/// </summary>
private Dictionary<string, string> GetAttributeEx(IAuthenticationResponse response)
{
var ret = new Dictionary<string, string>();
var fetchResponse = response.GetExtension<FetchResponse>();
if (fetchResponse == null) return ret;
var names = new List<string>();
var emails = new List<string>();
if (fetchResponse.Attributes.Contains("http://schema.openid.net/namePerson"))
names.AddRange(fetchResponse.Attributes["http://schema.openid.net/namePerson"].Values);
if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.FullName))
names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.FullName].Values);
if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.Alias))
names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.Alias].Values);
if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.First))
names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.First].Values);
if (fetchResponse.Attributes.Contains(WellKnownAttributes.Name.Last))
names.AddRange(fetchResponse.Attributes[WellKnownAttributes.Name.Last].Values);
if (fetchResponse.Attributes.Contains("http://schema.openid.net/contact/email"))
emails.AddRange(fetchResponse.Attributes["http://schema.openid.net/contact/email"].Values);
if (fetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email))
emails.AddRange(fetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values);
if (names.Count > 0)
ret["FullName"] = names[0];
if (emails.Count > 0)
ret["Email"] = emails[0];
return ret;
}
}
public static class OpenIdExtensions
{
public static Dictionary<string, string> ToDictionary(this ClaimsResponse response)
{
var map = new Dictionary<string, string>();
if (response == null) return map;
if (response.BirthDate.HasValue)
map["BirthDate"] = response.BirthDate.Value.ToJsv();
if (!response.BirthDateRaw.IsNullOrEmpty())
map["BirthDateRaw"] = response.BirthDateRaw;
if (!response.Country.IsNullOrEmpty())
map["Country"] = response.Country;
if (response.Culture != null)
map["Culture"] = response.Culture.TwoLetterISOLanguageName;
if (!response.Email.IsNullOrEmpty())
map["Email"] = response.Email;
if (!response.FullName.IsNullOrEmpty())
map["FullName"] = response.FullName;
if (response.Gender.HasValue)
map["Gender"] = response.Gender.Value.ToString();
if (!response.Language.IsNullOrEmpty())
map["Language"] = response.Language;
if (response.MailAddress != null)
map["MailAddress"] = response.MailAddress.ToJsv();
if (!response.Nickname.IsNullOrEmpty())
map["Nickname"] = response.Nickname;
if (!response.PostalCode.IsNullOrEmpty())
map["PostalCode"] = response.PostalCode;
if (!response.TimeZone.IsNullOrEmpty())
map["TimeZone"] = response.TimeZone;
return map;
}
}
}