gpt4 book ai didi

asp.net - 有没有办法使用 ASP.NET Identity 授权服务堆栈?

转载 作者:行者123 更新时间:2023-12-02 15:48:36 27 4
gpt4 key购买 nike

我发现的 ASP.NET MVC 和 Servicestack 之间相互身份验证的唯一示例涉及使用 Servicestack 的内置身份验证并为旧的 MVC Forms 身份验证设置 cookie。

我很感兴趣是否可以扭转这一局面并使用新的 ASP.NET 身份系统授权服务堆栈服务。

原因是我非常希望有一个简单的身份验证故事并使用相同的属性,例如带有 servicestack API 的 Identity 的 [Authorize] [AllowAnonymous]。

我没有使用 Identity 或 servicestack 插件的经验,因此如果其他人也有同样的想法,那就太好了。

最佳答案

我用自己的 AuthorizeAttribute 装饰了我的 servicestack 服务,该 AuthorizeAttribute 已连接到现有的 asp.net。也许这会对您有所帮助。

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();
}

}

关于asp.net - 有没有办法使用 ASP.NET Identity 授权服务堆栈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27180162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com