Reputation: 157
I wonder if it is possible to use ServiceStack on .NET core along with middleware.
My use case is that I'd like to have API implemented with ServiceStack, and use authorisation policies and openid connect middleware such as IdentityServer4.AccessTokenValidation.
If no, is there any alternative way to setup ServiceStack to work with openid connect server?
Upvotes: 3
Views: 823
Reputation: 157
I glued ServiceStack and .NET Core with the following code. I am not sure if it is the best way to archive the goal, but so far it works.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class AuthorizeAttribute : RequestFilterAsyncAttribute, IAuthorizeData
{
public AuthorizeAttribute(ApplyTo applyTo)
: base(applyTo)
{
Priority = -100;
}
public AuthorizeAttribute()
: this(ApplyTo.All)
{
}
public string Policy { get; set; }
public string Roles { get; set; }
public string AuthenticationSchemes { get; set; }
public override async Task ExecuteAsync(IRequest req, IResponse res, object requestDto)
{
var policyProvider = req.TryResolve<IAuthorizationPolicyProvider>();
var filter = new AuthorizeFilter(policyProvider, new[] {this});
var webRequest = req.OriginalRequest as HttpRequest;
var actionContext = new ActionContext(webRequest.HttpContext, new RouteData(), new ActionDescriptor());
var context = new AuthorizationFilterContext(actionContext, new List<IFilterMetadata>());
await filter.OnAuthorizationAsync(context);
if (context.Result is ChallengeResult)
{
res.StatusCode = 401;
res.EndRequest();
}
else if (context.Result is ForbidResult)
{
res.StatusCode = 403;
res.EndRequest();
}
}
}
Upvotes: 3
Reputation: 143319
You can register .NET Core Middleware in the same AppHost as ServiceStack in .NET Core Apps since ServiceStack is just another middleware in the pipeline itself but ServiceStack built-in Authentication attributes and features wont be aware about any external Authentication implementations.
For a more integrated solution check out the community contributed ServiceStack.Authentication.IdentityServer which includes a ServiceStack AuthProvider for IdentityServer.
Upvotes: 2