有没有一种方法来授权servicestack与ASP.NET身份? [英] Is there a way to authorise servicestack with ASP.NET Identity?
问题描述
我发现ASP.NET MVC和Servicestack之间的相互认证的唯一的例子,涉及到使用Servicestack内置的身份验证和设置老MVC窗体身份验证cookie的。
The only example I have found of mutual authentication between ASP.NET MVC and Servicestack involves using Servicestack's built in authentication and setting the cookie for old MVC Forms authentication.
我感兴趣的话,可以用新的ASP.NET识别系统围绕翻转这一点,并授权servicestack服务。
I am interested if it is possible to flip this around and authorise servicestack services with the new ASP.NET Identity system.
原因是,我在理想情况下想有一个简单的身份验证的故事,并使用相同的属性,如[授权] [使用AllowAnonymous]从身份与servicestack API。
The reason being that I would IDEALLY like to have a simple authentication story and use the same attributes, such as [Authorize] [AllowAnonymous] from Identity with the servicestack API.
我没有两个身份或servicestack插件的经验,所以这将是很好,如果别人在那里是想同样的事情。
I don't have experience with either Identity or servicestack plugins so it would be nice if someone else out there is thinking the same thing.
推荐答案
我饰我servicestack服务,用我自己的AuthorizeAttribute的挂钩到现有的asp.net。也许这会帮助你。
I decorated my servicestack services with my own AuthorizeAttribute that hooked into the existing asp.net. Maybe this will help you.
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(IRequest req, IResponse res, object requestDto)
{
if (!InternalAuthorize())
{
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.EndRequest();
}
}
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();
}
}
这篇关于有没有一种方法来授权servicestack与ASP.NET身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!