I know you have a better story for authentication, fresh, clean, no dependency, etc.
I know you have a better story for authorization, fresh, clean, no dependency, etc.
I know you have a better story for cache/session - fresh, clean, no dependency, not single threaded, etc.
However, what I have is an existing MVC website with WebApi and I am looking for something better - something like servicestack.
It is way too big of a project to try to swap out all the above. If I swap out authentication, I have to swap out cache and session.
I need a way to 'ease' into using servicestack, leveraging what I already have and then try to replace these other parts over time.
I spent a bunch of time reading and looking for a solution for the above and did not find one. Then I realized I did not have to use anything you had built, I could just create a RequestFilter and have that tie directly into what I already have in
asp.net. Maybe I should have figured that out sooner.
I am writing this in case it helps other people out in the future and/or in case you want to include some wiki pages on this and/or include the code I wrote in one of the contribs.
Anyway, I wrote a simple RequestFilterAttribute that looked at HttpContext.Current and did the same authorization
asp.net does. Looks at IsAuthenticated and checks the roles the user is in. If you have any suggestions or see any problems, let me know - but my initial testing shows this works great.
public class ServiceStackToAspNetAuthorizeAttribute : RequestFilterAttribute
{
private string _roles;
private string[] _rolesSplit = new string[0];
public string Roles
{
get { return _roles ?? String.Empty; }
set
{
_roles = value;
_rolesSplit = SplitString(value);
}
}
public ServiceStackToAspNetAuthorizeAttribute(ApplyTo applyTo)
: base(applyTo)
{
this.Priority = (int)RequestFilterPriority.Authenticate;
}
public ServiceStackToAspNetAuthorizeAttribute()
: this(ApplyTo.All) { }
public override void Execute(IHttpRequest req, IHttpResponse res, object requestDto)
{
if (!InternalAuthorize())
{
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.EndServiceStackRequest();
}
}
private bool InternalAuthorize()
{
var context = HttpContext.Current;
if (context != null)
{
var user = context.User;
if (user != null)
{
if (!user.Identity.IsAuthenticated)
return false;
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole))
return false;
return true;
}
}
return false;
}
private static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
{
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}