forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAuthService.cs
More file actions
215 lines (173 loc) · 6.63 KB
/
AuthService.cs
File metadata and controls
215 lines (173 loc) · 6.63 KB
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
using System;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Net;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.ServiceModel;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.ServiceInterface.Auth
{
/// <summary>
/// Inject logic into existing services by introspecting the request and injecting your own
/// validation logic. Exceptions thrown will have the same behaviour as if the service threw it.
///
/// If a non-null object is returned the request will short-circuit and return that response.
/// </summary>
/// <param name="service">The instance of the service</param>
/// <param name="httpMethod">GET,POST,PUT,DELETE</param>
/// <param name="requestDto"></param>
/// <returns>Response DTO; non-null will short-circuit execution and return that response</returns>
public delegate object ValidateFn(IServiceBase service, string httpMethod, object requestDto);
public class Auth
{
public string provider { get; set; }
public string State { get; set; }
public string oauth_token { get; set; }
public string oauth_verifier { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class AuthResponse
{
public AuthResponse()
{
this.ResponseStatus = new ResponseStatus();
}
public string SessionId { get; set; }
public string UserName { get; set; }
public ResponseStatus ResponseStatus { get; set; }
}
public class AuthService : RestServiceBase<Auth>
{
public const string BasicProvider = "basic";
public const string CredentialsProvider = "credentials";
public static string DefaultOAuthProvider { get; private set; }
public static string DefaultOAuthRealm { get; private set; }
public static AuthConfig[] AuthConfigs { get; private set; }
public static Func<IOAuthSession> SessionFactory { get; private set; }
public static ValidateFn ValidateFn { get; set; }
public static string GetSessionKey(string sessionId)
{
return IdUtils.CreateUrn<IOAuthSession>(sessionId);
}
public static void Init(IAppHost appHost, Func<IOAuthSession> sessionFactory, params AuthConfig[] authConfigs)
{
if (authConfigs.Length == 0)
throw new ArgumentNullException("authConfigs");
DefaultOAuthProvider = authConfigs[0].Provider;
DefaultOAuthRealm = authConfigs[0].AuthRealm;
AuthConfigs = authConfigs;
SessionFactory = sessionFactory;
appHost.RegisterService<AuthService>();
SessionFeature.Init(appHost);
appHost.RequestFilters.Add((req, res, dto) => {
var requiresAuth = dto.GetType().FirstAttribute<AuthenticateAttribute>();
if (requiresAuth != null)
{
var matchingOAuthConfigs = AuthConfigs.Where(x =>
requiresAuth.Provider.IsNullOrEmpty()
|| x.Provider == requiresAuth.Provider).ToList();
if (matchingOAuthConfigs.Count == 0)
{
res.WriteError(req, dto, "No OAuth Configs found matching {0} provider"
.Fmt(requiresAuth.Provider ?? "any"));
res.Close();
return;
}
using (var cache = appHost.GetCacheClient())
{
var sessionId = req.GetPermanentSessionId();
var session = sessionId != null ? cache.GetSession(sessionId) : null;
if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
{
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.AddHeader(HttpHeaders.WwwAuthenticate, "OAuth realm=\"{0}\"".Fmt(matchingOAuthConfigs[0].AuthRealm));
res.Close();
return;
}
}
}
});
}
private void AssertAuthProviders()
{
if (AuthConfigs == null || AuthConfigs.Length == 0)
throw new ConfigurationException("No OAuth providers have been registered in your AppHost.");
}
public override object OnGet(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Get, request);
if (response != null) return response;
}
AssertAuthProviders();
var provider = request.provider ?? AuthConfigs[0].Provider;
if (provider == BasicProvider || provider == CredentialsProvider)
{
return CredentialsAuth(request);
}
var oAuthConfig = AuthConfigs.FirstOrDefault(x => x.Provider == provider);
if (oAuthConfig == null)
throw HttpError.NotFound("No configuration was added for OAuth provider '{0}'".Fmt(provider));
var session = this.GetSession();
if (oAuthConfig.CallbackUrl.IsNullOrEmpty())
oAuthConfig.CallbackUrl = base.RequestContext.AbsoluteUri;
if (session.ReferrerUrl.IsNullOrEmpty())
session.ReferrerUrl = base.RequestContext.GetHeader("Referer") ?? oAuthConfig.CallbackUrl;
var oAuth = new OAuthAuthorizer(oAuthConfig);
if (!session.IsAuthorized(provider))
{
var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == provider);
if (tokens == null)
session.ProviderOAuthAccess.Add(tokens = new OAuthTokens { Provider = provider });
return oAuthConfig.Authenticate(this, request, session, tokens, oAuth);
}
//Already Authenticated
return this.Redirect(session.ReferrerUrl.AddQueryParam("s", "0"));
}
public override object OnPost(Auth request)
{
if (ValidateFn != null)
{
var response = ValidateFn(this, HttpMethods.Get, request);
if (response != null) return response;
}
return CredentialsAuth(request);
}
private object CredentialsAuth(Auth request)
{
AssertAuthProviders();
request.provider.ThrowIfNullOrEmpty("provider");
if (request.provider != BasicProvider && request.provider != CredentialsProvider)
throw new ArgumentException("Provider must be either 'basic' or 'credentials'");
var session = this.GetSession();
var userName = request.UserName;
var password = request.Password;
if (request.provider == BasicProvider)
{
var httpReq = base.RequestContext.Get<IHttpRequest>();
var basicAuth = httpReq.GetBasicAuthUserAndPassword();
if (basicAuth == null)
throw HttpError.Unauthorized("Invalid BasicAuth credentials");
userName = basicAuth.Value.Key;
password = basicAuth.Value.Value;
}
if (session.TryAuthenticate(this, userName, password))
{
this.SaveSession(session);
return new AuthResponse {
UserName = userName,
SessionId = session.Id,
};
}
throw HttpError.Unauthorized("Invalid UserName or Password");
}
}
}