forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthenticateAttribute.cs
More file actions
142 lines (125 loc) · 5.71 KB
/
AuthenticateAttribute.cs
File metadata and controls
142 lines (125 loc) · 5.71 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
using System;
using System.Linq;
using ServiceStack.Common;
using ServiceStack.Common.Web;
using ServiceStack.ServiceHost;
using ServiceStack.ServiceInterface.Auth;
using ServiceStack.Text;
using ServiceStack.WebHost.Endpoints.Extensions;
namespace ServiceStack.ServiceInterface
{
/// <summary>
/// Indicates that the request dto, which is associated with this attribute,
/// requires authentication.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class AuthenticateAttribute : RequestFilterAttribute
{
/// <summary>
/// Restrict authentication to a specific <see cref="IAuthProvider"/>.
/// For example, if this attribute should only permit access
/// if the user is authenticated with <see cref="BasicAuthProvider"/>,
/// you should set this property to <see cref="BasicAuthProvider.Name"/>.
/// </summary>
public string Provider { get; set; }
/// <summary>
/// Redirect the client to a specific URL if authentication failed.
/// If this property is null, simply `401 Unauthorized` is returned.
/// </summary>
public string HtmlRedirect { get; set; }
public AuthenticateAttribute(ApplyTo applyTo)
: base(applyTo)
{
this.Priority = (int) RequestFilterPriority.Authenticate;
}
public AuthenticateAttribute()
: this(ApplyTo.All) {}
public AuthenticateAttribute(string provider)
: this(ApplyTo.All)
{
this.Provider = provider;
}
public AuthenticateAttribute(ApplyTo applyTo, string provider)
: this(applyTo)
{
this.Provider = provider;
}
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
if (AuthService.AuthProviders == null) throw new InvalidOperationException("The AuthService must be initialized by calling "
+ "AuthService.Init to use an authenticate attribute");
var matchingOAuthConfigs = AuthService.AuthProviders.Where(x =>
this.Provider.IsNullOrEmpty()
|| x.Provider == this.Provider).ToList();
if (matchingOAuthConfigs.Count == 0)
{
res.WriteError(req, requestDto, "No OAuth Configs found matching {0} provider"
.Fmt(this.Provider ?? "any"));
res.EndServiceStackRequest();
return;
}
if (matchingOAuthConfigs.Any(x => x.Provider == DigestAuthProvider.Name))
AuthenticateIfDigestAuth(req, res);
if (matchingOAuthConfigs.Any(x => x.Provider == BasicAuthProvider.Name))
AuthenticateIfBasicAuth(req, res);
using (var cache = req.GetCacheClient())
{
var session = req.GetSession();
if (session == null || !matchingOAuthConfigs.Any(x => session.IsAuthorized(x.Provider)))
{
var htmlRedirect = HtmlRedirect ?? AuthService.HtmlRedirect;
if (htmlRedirect != null && req.ResponseContentType.MatchesContentType(ContentType.Html))
{
var url = htmlRedirect;
if (url.SafeSubstring(0, 2) == "~/")
{
url = req.GetBaseUrl().CombineWith(url.Substring(2));
}
url = url.AddQueryParam("redirect", req.AbsoluteUri);
res.RedirectToUrl(url);
return;
}
AuthProvider.HandleFailedAuth(matchingOAuthConfigs[0], session, req, res);
}
}
}
public static void AuthenticateIfBasicAuth(IHttpRequest req, IHttpResponse res)
{
//Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()
var userPass = req.GetBasicAuthUserAndPassword();
if (userPass != null)
{
var authService = req.TryResolve<AuthService>();
authService.RequestContext = new HttpRequestContext(req, res, null);
var response = authService.Post(new Auth.Auth {
provider = BasicAuthProvider.Name,
UserName = userPass.Value.Key,
Password = userPass.Value.Value
});
}
}
public static void AuthenticateIfDigestAuth(IHttpRequest req, IHttpResponse res)
{
//Need to run SessionFeature filter since its not executed before this attribute (Priority -100)
SessionFeature.AddSessionIdToRequestFilter(req, res, null); //Required to get req.GetSessionId()
var digestAuth = req.GetDigestAuth();
if (digestAuth != null)
{
var authService = req.TryResolve<AuthService>();
authService.RequestContext = new HttpRequestContext(req, res, null);
var response = authService.Post(new Auth.Auth
{
provider = DigestAuthProvider.Name,
nonce = digestAuth["nonce"],
uri = digestAuth["uri"],
response = digestAuth["response"],
qop = digestAuth["qop"],
nc = digestAuth["nc"],
cnonce = digestAuth["cnonce"],
UserName = digestAuth["username"]
});
}
}
}
}