2 // System.Web.Security.RolePrincipal
5 // Ben Maurer (bmaurer@users.sourceforge.net)
6 // Sebastien Pouliot <sebastien@ximian.com>
9 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections.Specialized;
32 using System.Security.Permissions;
33 using System.Security.Principal;
34 using System.Web.Configuration;
35 using System.Web.Util;
39 namespace System.Web.Security {
42 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
48 class RolePrincipal : IPrincipal {
52 string[] _cachedArray;
53 HybridDictionary _cachedRoles;
54 readonly string _providerName;
62 public RolePrincipal (IIdentity identity)
65 throw new ArgumentNullException ("identity");
67 this._identity = identity;
68 this._cookiePath = RoleManagerConfig.CookiePath;
69 this._issueDate = DateTime.Now;
70 this._expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout);
73 public RolePrincipal (IIdentity identity, string encryptedTicket)
76 DecryptTicket (encryptedTicket);
79 public RolePrincipal (string providerName, IIdentity identity)
82 if (providerName == null)
83 throw new ArgumentNullException ("providerName");
85 this._providerName = providerName;
88 public RolePrincipal (string providerName, IIdentity identity, string encryptedTicket)
89 : this (providerName, identity)
91 DecryptTicket (encryptedTicket);
94 public string [] GetRoles ()
96 if (!_identity.IsAuthenticated)
99 if (!IsRoleListCached || Expired) {
100 _cachedArray = Provider.GetRolesForUser (_identity.Name);
101 _cachedRoles = new HybridDictionary (true);
103 foreach (string r in _cachedArray)
104 _cachedRoles.Add(r, r);
112 public bool IsInRole (string role)
114 if (!_identity.IsAuthenticated)
119 return _cachedRoles [role] != null;
122 public string ToEncryptedTicket ()
124 string roles = string.Join (",", GetRoles ());
125 string cookiePath = RoleManagerConfig.CookiePath;
126 int approxTicketLen = roles.Length + cookiePath.Length + 64;
128 if (_cachedArray.Length > Roles.MaxCachedResults)
131 MemoryStream ticket = new MemoryStream (approxTicketLen);
132 BinaryWriter writer = new BinaryWriter (ticket);
135 writer.Write (Version);
138 DateTime issueDate = DateTime.Now;
139 writer.Write (issueDate.Ticks);
141 // expiration datetime
142 writer.Write (_expireDate.Ticks);
144 writer.Write (cookiePath);
145 writer.Write (roles);
147 CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
149 byte[] ticket_data = ticket.GetBuffer ();
150 if (cookieProtection == CookieProtection.All) {
151 ticket_data = MachineKeySectionUtils.EncryptSign (MachineConfig, ticket_data);
152 } else if (cookieProtection == CookieProtection.Encryption) {
153 ticket_data = MachineKeySectionUtils.Encrypt (MachineConfig, ticket_data);
154 } else if (cookieProtection == CookieProtection.Validation) {
155 ticket_data = MachineKeySectionUtils.Sign (MachineConfig, ticket_data);
158 return GetBase64FromBytes (ticket_data, 0, ticket_data.Length);
161 void DecryptTicket (string encryptedTicket)
163 if (encryptedTicket == null || encryptedTicket == String.Empty)
164 throw new ArgumentException ("Invalid encrypted ticket", "encryptedTicket");
166 byte [] ticketBytes = GetBytesFromBase64 (encryptedTicket);
167 byte [] decryptedTicketBytes = null;
169 CookieProtection cookieProtection = RoleManagerConfig.CookieProtection;
171 if (cookieProtection == CookieProtection.All) {
172 decryptedTicketBytes = MachineKeySectionUtils.VerifyDecrypt (MachineConfig, ticketBytes);
173 } else if (cookieProtection == CookieProtection.Encryption) {
174 decryptedTicketBytes = MachineKeySectionUtils.Decrypt (MachineConfig, ticketBytes);
175 } else if (cookieProtection == CookieProtection.Validation) {
176 decryptedTicketBytes = MachineKeySectionUtils.Verify (MachineConfig, ticketBytes);
179 if (decryptedTicketBytes == null)
180 throw new HttpException ("ticket validation failed");
182 MemoryStream ticket = new MemoryStream (decryptedTicketBytes);
183 BinaryReader reader = new BinaryReader (ticket);
186 _version = reader.ReadInt32 ();
189 _issueDate = new DateTime (reader.ReadInt64 ());
192 _expireDate = new DateTime (reader.ReadInt64 ());
195 _cookiePath = reader.ReadString ();
198 string roles = reader.ReadString ();
201 InitializeRoles (roles);
202 //update ticket if less than half of CookieTimeout remaining.
203 if (Roles.CookieSlidingExpiration){
204 if (_expireDate-DateTime.Now < TimeSpan.FromTicks (RoleManagerConfig.CookieTimeout.Ticks/2)) {
205 _issueDate = DateTime.Now;
206 _expireDate = DateTime.Now.Add (RoleManagerConfig.CookieTimeout);
211 // issue a new ticket
212 _issueDate = DateTime.Now;
213 _expireDate = _issueDate.Add (RoleManagerConfig.CookieTimeout);
217 void InitializeRoles (string decryptedRoles)
219 _cachedArray = decryptedRoles.Split (',');
220 _cachedRoles = new HybridDictionary (true);
222 foreach (string r in _cachedArray)
223 _cachedRoles.Add (r, r);
226 public bool CachedListChanged {
227 get { return _listChanged; }
230 public string CookiePath {
231 get { return _cookiePath; }
234 public bool Expired {
235 get { return ExpireDate < DateTime.Now; }
238 public DateTime ExpireDate {
239 get { return _expireDate; }
242 public IIdentity Identity {
243 get { return _identity; }
246 public bool IsRoleListCached {
247 get { return (_cachedRoles != null) && RoleManagerConfig.CacheRolesInCookie; }
250 public DateTime IssueDate {
251 get { return _issueDate; }
254 public string ProviderName {
255 get { return String.IsNullOrEmpty(_providerName) ? Provider.Name : _providerName; }
259 get { return _version; }
262 RoleProvider Provider {
264 if (String.IsNullOrEmpty (_providerName))
265 return Roles.Provider;
267 return Roles.Providers [_providerName];
271 public void SetDirty ()
278 static string GetBase64FromBytes (byte [] bytes, int offset, int len)
280 return Convert.ToBase64String (bytes, offset, len);
283 static byte [] GetBytesFromBase64 (string base64String)
285 return Convert.FromBase64String (base64String);
288 RoleManagerSection RoleManagerConfig
290 get { return (RoleManagerSection) WebConfigurationManager.GetSection ("system.web/roleManager"); }
293 MachineKeySection MachineConfig
295 get { return (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey"); }