Is there a way to authorise servicestack with ASP.

2019-05-06 02:09发布

问题:

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.

I am interested if it is possible to flip this around and authorise servicestack services with the new ASP.NET Identity system.

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.

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.

回答1:

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

}