I’m using Swashbuckle (5.3.2) and it generates a nice API documentation.
To clarify my problem, I set up a small example project with no real meaning.
The API can only be used with a valid API key.
For that I introduced an ApiKeyFilter which validates the api_key and read out corresponding roles.
ApiKeyFilter
public class ApiKeyFilter : IAuthenticationFilter
{
private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
private readonly string authenticationScheme = "Bearer";
private readonly string queryStringApiKey = "api_key";
public bool AllowMultiple
{
get { return false; }
}
public ApiKeyFilter()
{
if (allowedApps.Count == 0)
{
allowedApps.Add("PetLover_api_key", new []{"PetLover"});
allowedApps.Add("CarOwner_api_key", new []{"CarOwner"});
allowedApps.Add("Admin_api_key", new []{"PetLover","CarOwner"});
}
}
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
var req = context.Request;
Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
string rawAuthzHeader = null;
if (queryStrings.ContainsKey(queryStringApiKey))
{
rawAuthzHeader = queryStrings[queryStringApiKey];
}
else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
rawAuthzHeader = req.Headers.Authorization.Parameter;
}
if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
context.Principal = currentPrincipal;
}
else
{
context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
}
return Task.FromResult(0);
}
public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
context.Result = new ResultWithChallenge(context.Result);
return Task.FromResult(0);
}
}
public class ResultWithChallenge : IHttpActionResult
{
private readonly string authenticationScheme = "amx";
private readonly IHttpActionResult next;
public ResultWithChallenge(IHttpActionResult next)
{
this.next = next;
}
public async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = await next.ExecuteAsync(cancellationToken);
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
response.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue(authenticationScheme));
}
return response;
}
}
The controller/resources can only be accessed if the requester has the corresponding role.
PetController
[Authorize(Roles = "PetLover")]
[RoutePrefix("api/pets")]
public class PetController : ApiController
{
// GET api/pet
[Route]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/pet/5
[Route("{id:int}")]
public string Get(int id)
{
return "value";
}
// POST api/pet
[Route]
public void Post([FromBody]string value)
{
}
// PUT api/pet/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/pet/5
public void Delete(int id)
{
}
}
CarController
[RoutePrefix("api/cars")]
public class CarController : ApiController
{
// GET api/car
[AllowAnonymous]
[Route]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/car/5
[Authorize(Roles = "CarOwner")]
[Route("{id:int}")]
public string Get(int id)
{
return "value";
}
// POST api/car
[Authorize(Roles = "CarOwner")]
[Route]
public void Post([FromBody]string value)
{
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Filters.Add(new ApiKeyFilter());
//config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
}
}
So far so good. No problem here.
Question:
Now I want that the ‘User’ roles are taken into account during the API generation. I only want to display the resources and actions in the documentation which the user can consume with this api_key.
The output should somehow look like (/swagger/ui/index?api_key=XXX):
Admin_api_key:
Car
get /api/cars
post /api/cars
get /api/cars/{id}
Pet
get /api/pets
post /api/pets
get /api/pets/{id}
CarOwner_api_key:
Car
get /api/cars
post /api/cars
get /api/cars/{id}
PetLover_api_key:
Car
get /api/cars
Pet
get /api/pets
post /api/pets
get /api/pets/{id}
invalid_api_key:
Nothing to display
I don’t have access to the HttpRequest during the API specification generation to read out any query string or any header information.
I already had a look into a DelegatingHandler but I have trouble to read out the Principal in any Swashbuckle filter (OperationFilter, DocumentFilter) and I’m also not able to read out the Principal in a CustomProvider.
public class CustomAuthenticationMessageHandler : DelegatingHandler
{
private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
private readonly string authenticationScheme = "Bearer";
private readonly string queryStringApiKey = "api_key";
public bool AllowMultiple
{
get { return false; }
}
public CustomAuthenticationMessageHandler()
{
if (allowedApps.Count == 0)
{
allowedApps.Add("PetLover_api_key", new[] {"PetLover"});
allowedApps.Add("CarOwner_api_key", new[] {"CarOwner"});
allowedApps.Add("Admin_api_key", new[] {"PetLover", "CarOwner"});
}
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var req = request;
Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
string rawAuthzHeader = null;
if (queryStrings.ContainsKey(queryStringApiKey))
{
rawAuthzHeader = queryStrings[queryStringApiKey];
}
else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
rawAuthzHeader = req.Headers.Authorization.Parameter;
}
if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
request.GetRequestContext().Principal = currentPrincipal;
}
else
{
}
return await base.SendAsync(request, cancellationToken);
}
}
I found some similar question/issues but no real answer.
Web API Documentation using swagger
Restrict access to certain API controllers in Swagger using Swashbuckle and ASP.NET Identity
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/334
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/735
{hxxps://}github.com/domaindrivendev/Swashbuckle/issues/478
I now found a solution which works for me.
I used the CustomAuthenticationMessageHandler (same as in my question) to put the rules into the HttpContext.
public class CustomAuthenticationMessageHandler : DelegatingHandler
{
private static Dictionary<string, String[]> allowedApps = new Dictionary<string, String[]>();
private readonly string authenticationScheme = "Bearer";
private readonly string queryStringApiKey = "api_key";
public bool AllowMultiple
{
get { return false; }
}
public CustomAuthenticationMessageHandler()
{
if (allowedApps.Count == 0)
{
allowedApps.Add("PetLover_api_key", new[] {"PetLover"});
allowedApps.Add("CarOwner_api_key", new[] {"CarOwner"});
allowedApps.Add("Admin_api_key", new[] {"PetLover", "CarOwner"});
}
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var req = request;
Dictionary<string, string> queryStrings = req.GetQueryNameValuePairs().ToDictionary(x => x.Key.ToLower(), x => x.Value);
string rawAuthzHeader = null;
if (queryStrings.ContainsKey(queryStringApiKey))
{
rawAuthzHeader = queryStrings[queryStringApiKey];
}
else if (req.Headers.Authorization != null && authenticationScheme.Equals(req.Headers.Authorization.Scheme, StringComparison.OrdinalIgnoreCase))
{
rawAuthzHeader = req.Headers.Authorization.Parameter;
}
if (rawAuthzHeader != null && allowedApps.ContainsKey(rawAuthzHeader))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(rawAuthzHeader), allowedApps[rawAuthzHeader]);
request.GetRequestContext().Principal = currentPrincipal;
}
else
{
}
return await base.SendAsync(request, cancellationToken);
}
}
I introduced an custom Swashbuckle IDocumentFilter which reads out the rules from the HttpContext and remove the actions and resources from the SwaggerDocument which are not allowed for this rules (based on api_key).
public class AuthorizeRoleFilter : IDocumentFilter
{
public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, IApiExplorer apiExplorer)
{
IPrincipal user = HttpContext.Current.User;
foreach (ApiDescription apiDescription in apiExplorer.ApiDescriptions)
{
var authorizeAttributes = apiDescription
.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>().ToList();
authorizeAttributes.AddRange(apiDescription
.ActionDescriptor.ControllerDescriptor.GetCustomAttributes<AuthorizeAttribute>());
if (!authorizeAttributes.Any())
continue;
var roles =
authorizeAttributes
.SelectMany(attr => attr.Roles.Split(','))
.Distinct()
.ToList();
if (!user.Identity.IsAuthenticated || !roles.Any(role => user.IsInRole(role) || role == ""))
{
string key = "/" + apiDescription.RelativePath;
PathItem pathItem = swaggerDoc.paths[key];
switch (apiDescription.HttpMethod.Method.ToLower())
{
case "get":
pathItem.get = null;
break;
case "put":
pathItem.put = null;
break;
case "post":
pathItem.post = null;
break;
case "delete":
pathItem.delete = null;
break;
case "options":
pathItem.options = null;
break;
case "head":
pathItem.head = null;
break;
case "patch":
pathItem.patch = null;
break;
}
if (pathItem.get == null &&
pathItem.put == null &&
pathItem.post == null &&
pathItem.delete == null &&
pathItem.options == null &&
pathItem.head == null &&
pathItem.patch == null)
{
swaggerDoc.paths.Remove(key);
}
}
}
swaggerDoc.paths = swaggerDoc.paths.Count == 0 ? null : swaggerDoc.paths;
swaggerDoc.definitions = swaggerDoc.paths == null ? null : swaggerDoc.definitions;
}
}
My WebApiConfig now looks like this. I removed my ApiKeyFilter because it is not needed anymore.
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//config.Filters.Add(new ApiKeyFilter());
config.MessageHandlers.Add(new CustomAuthenticationMessageHandler());
}
}
SwaggerConfig
public class SwaggerConfig
{
public static void Register()
{
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "SwashbuckleExample");
c.DocumentFilter<AuthorizeRoleFilter>();
})
.EnableSwaggerUi(c => { });
}
}
Additional
In my project I used a CustomProvider which cache the SwaggerDocument per api_key.
public class CachingSwaggerProvider : ISwaggerProvider
{
private static ConcurrentDictionary<string, SwaggerDocument> _cache =
new ConcurrentDictionary<string, SwaggerDocument>();
private readonly ISwaggerProvider _swaggerProvider;
public CachingSwaggerProvider(ISwaggerProvider swaggerProvider)
{
_swaggerProvider = swaggerProvider;
}
public SwaggerDocument GetSwagger(string rootUrl, string apiVersion)
{
HttpContext httpContext = HttpContext.Current;
string name = httpContext.User.Identity.Name;
var cacheKey = string.Format("{0}_{1}_{2}", rootUrl, apiVersion, name);
return _cache.GetOrAdd(cacheKey, (key) => _swaggerProvider.GetSwagger(rootUrl, apiVersion));
}
}
Related
I am identity 2.1.2 with asp.net core 2.0, I have application claim table which have claim type and claim value
i.e Assets ,Assets Edit,Assets, Assets View, where claim types are same with distinct claim values and I am creating policies using claim type name which is working fine for me no clue about how to add multiple policies in one action. Below code is being used in startup file to create policies.
services.AddAuthorization(options =>
{
var dbContext = SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder<MyDBContext>(),
Configuration.GetConnectionString("TestIdentityClaimAuth")).Options;
var dbCon = new MyDBContext(dbContext);
//Getting the list of application claims.
var applicationClaims = dbCon.ApplicationClaims.ToList();
var strClaimValues = string.Empty;
List<ClaimVM> lstClaimTypeVM = new List<ClaimVM>();
IEnumerable<string> lstClaimValueVM = null;// new IEnumerable<string>();
lstClaimTypeVM = (from dbAppClaim
in dbCon.ApplicationClaims
select new ClaimVM
{
ClaimType = dbAppClaim.ClaimType
}).Distinct().ToList();
foreach (ClaimVM objClaimType in lstClaimTypeVM)
{
lstClaimValueVM = (from dbClaimValues in dbCon.ApplicationClaims
where dbClaimValues.ClaimType == objClaimType.ClaimType
select dbClaimValues.ClaimValue).ToList();
options.AddPolicy(objClaimType.ClaimType, policy => policy.RequireClaim(objClaimType.ClaimType, lstClaimValueVM));
lstClaimValueVM = null;
}
});
And in my controller using the Autherize attribute like this.
[Authorize(Policy = "Assets Edit")]
Please shade some light on it thanks in advance.
For multiple policys, you could implement your own AuthorizeAttribute.
MultiplePolicysAuthorizeAttribute
public class MultiplePolicysAuthorizeAttribute : TypeFilterAttribute
{
public MultiplePolicysAuthorizeAttribute(string policys, bool isAnd = false) : base(typeof(MultiplePolicysAuthorizeFilter))
{
Arguments = new object[] { policys, isAnd };
}
}
MultiplePolicysAuthorizeFilter
public class MultiplePolicysAuthorizeFilter : IAsyncAuthorizationFilter
{
private readonly IAuthorizationService _authorization;
public string Policys { get; private set; }
public bool IsAnd { get; private set; }
public MultiplePolicysAuthorizeFilter(string policys, bool isAnd, IAuthorizationService authorization)
{
Policys = policys;
IsAnd = isAnd;
_authorization = authorization;
}
public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
{
var policys = Policys.Split(";").ToList();
if (IsAnd)
{
foreach (var policy in policys)
{
var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy);
if (!authorized.Succeeded)
{
context.Result = new ForbidResult();
return;
}
}
}
else
{
foreach (var policy in policys)
{
var authorized = await _authorization.AuthorizeAsync(context.HttpContext.User, policy);
if (authorized.Succeeded)
{
return;
}
}
context.Result = new ForbidResult();
return;
}
}
}
only require one of the policy
[MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete")]
only require all the policys
[MultiplePolicysAuthorize("Assets View;Assets Edit;Assets Delete", true)]
If you simply want to apply multiple policies, you can do this:
[Authorize(Policy = "Asset")]
[Authorize(Policy = "Edit")]
public class MyController : Controller {
}
EDIT: to clarify, this is additive - you must pass both policy requirements.
You can use make multiple requirements class implementing IAuthorizationRequirement, and register to the DI container the multiple requirements handlers of AuthorizationHandler.
So you can simply add them to your Policy using the AddRequirement inside AuthorizationPolicyBuilder
public AuthorizationPolicyBuilder AddRequirements(params IAuthorizationRequirement[] requirements);
Startup.cs:
services.AddScoped<IAuthorizationHandler, FooHandler>();
services.AddScoped<IAuthorizationHandler, BooHandler>();
services.AddAuthorization(authorizationOptions =>
{
authorizationOptions.AddPolicy(
"FooAndBooPolicy",
policyBuilder =>
{
policyBuilder.RequireAuthenticatedUser();
policyBuilder.AddRequirements(new FooRequirement(), new BooRequirement());
});
});
Requirements.cs:
public class FooRequirement : IAuthorizationRequirement { }
public class FooHandler : AuthorizationHandler<FooRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationContext context, FooRequirement requirement)
{
if (context.User.HasClaim(c => c.Type == "Foo" && c.Value == true))
{
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
public class BooRequirement : IAuthorizationRequirement { }
public class BooHandler : AuthorizationHandler<BooRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationContext context, BooRequirement requirement)
{
if (context.User.HasClaim(c => c.Type == "Boo" && c.Value == true))
{
context.Succeed(requirement);
return Task.FromResult(0);
}
}
}
I want to do a custom AuthorizeAttribute. I want to use the IMemoryCache to store the tokens and i'm using a custom provider to inject the IMemoryCache instance. My problem is after OnAuthorization method it is not called my controller's action and it throws an internal server error that i'm not able to catch.
And here is the implementation so far
public class ApiAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public IMemoryCache Cache { get; set; }
/// <summary>
/// Verifica se o token é válido na sessão
/// </summary>
/// <param name="httpContext"></param>
/// <returns></returns>
public void OnAuthorization(AuthorizationFilterContext context)
{
//Check we have a valid HttpContext
if (context.HttpContext == null)
throw new ArgumentNullException("httpContext");
string token;
token = context.HttpContext.Request.QueryString.Value;
if (String.IsNullOrEmpty(token))
token = context.HttpContext.Request.Form["token"];
if (String.IsNullOrEmpty(token))
{
context.Result = new UnauthorizedResult();
return;
}
if (Cache == null)
{
context.Result = new UnauthorizedResult();
return;
}
if (token.Contains("="))
{
token = token.Split('=')[1];
}
var tokens = Cache.Get<Dictionary<string, User>>("tokens");
var result = (from t in tokens where t.Key == token select t.Value).ToList();
var controller = (string)context.RouteData.Values["controller"];
var action = (string)context.RouteData.Values["action"];
if (result.Count < 1)
context.Result = new UnauthorizedResult();
}
}
public class CacheProvider : IApplicationModelProvider
{
private IMemoryCache _cache;
public CacheProvider(IMemoryCache cache)
{
_cache = cache;
}
public int Order { get { return -1000 + 10; } }
public void OnProvidersExecuted(ApplicationModelProviderContext context)
{
foreach (var controllerModel in context.Result.Controllers)
{
// pass the depencency to controller attibutes
controllerModel.Attributes
.OfType<ApiAuthorizeAttribute>().ToList()
.ForEach(a => a.Cache = _cache);
// pass the dependency to action attributes
controllerModel.Actions.SelectMany(a => a.Attributes)
.OfType<ApiAuthorizeAttribute>().ToList()
.ForEach(a => a.Cache = _cache);
}
}
public void OnProvidersExecuting(ApplicationModelProviderContext context)
{
// intentionally empty
}
}
And here is the controller
[ApiAuthorize]
[HttpPost]
public JsonResult Delete([FromForm] string inputId)
{
//Do stuff
}
Thank in advance
After some digging i found this way to do this, i dont know if it is the best way to achieve that
I Created a policy requirement
public class TokenRequirement : IAuthorizationRequirement
{
}
And an AuthorizationHandler
public class TokenRequirementHandler : AuthorizationHandler<TokenRequirement>
{
public IMemoryCache Cache { get; set; }
public TokenRequirementHandler(IMemoryCache memoryCache)
{
Cache = memoryCache;
}
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TokenRequirement requirement)
{
return Task.Run(() => { //access the cache and then
context.Succeed(requirement); });
}
}
On my Startup i registered the handler and add the Authorization
services.AddAuthorization(options =>
{
options.AddPolicy("Token",
policy => policy.Requirements.Add(new Authorize.TokenRequirement()));
});
services.AddSingleton<IAuthorizationHandler, Authorize.TokenRequirementHandler>();
In the controller i used the Authorize attribute
[Authorize(Policy = "Token")]
[HttpPost]
public JsonResult Delete([FromForm] string inputId)
{
//Do stuff
}
And now it works.
Thank you.
I'm using Owin and UseWsFederationAuthentication() in AspNetCore MVC 1.0.0. app. Authentication works perfectly but i cant SignOut the user.
This code
public class AccountController : Controller
{
public async Task<IActionResult> SignOut()
{
await this.HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationType);
return RedirectToAction("Index", "Test");
}
}
Throws:
InvalidOperationException: No authentication handler is configured to handle the scheme: Cookies
The HttpContext.Authentication is set to Microsoft.AspNetCore.Http.Authentication.Internal.DefaultAuthenticationManager
Startup.cs:Configure
app.UseOwinAppBuilder(builder =>
{
var authConfig = new WsFederationAuthenticationSettings
{
MetadataAddress = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:MetadataAddress"),
Realm = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:Realm"),
UseCookieSlidingExpiration = this.Configuration.GetValue<bool>("Eyc.Sdk:Authentication:WsFederation:UseCookieSlidingExpiration"),
CookieExpireTimeSpan = this.Configuration.GetValue<string>("Eyc.Sdk:Authentication:WsFederation:CookieExpireTimeSpan")
};
builder.UseEycAuthentication(authConfig, app.ApplicationServices);
});
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action<global::Owin.IAppBuilder> configuration)
{
return app.UseOwin(setup => setup(next =>
{
var builder = new AppBuilder();
var lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
var properties = new AppProperties(builder.Properties);
properties.AppName = app.ApplicationServices.GetApplicationUniqueIdentifier();
properties.OnAppDisposing = lifetime.ApplicationStopping;
properties.DefaultApp = next;
configuration(builder);
return builder.Build<Func<IDictionary<string, object>, Task>>();
}));
}
}
public static class AppBuilderExtensions
{
public static IAppBuilder UseEycAuthentication(
this IAppBuilder app,
WsFederationAuthenticationSettings authenticationSettings,
IServiceProvider serviceProvider,
bool authenticateEveryRequest = true)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
if (authenticationSettings == null)
{
throw new ArgumentNullException(nameof(authenticationSettings));
}
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
return app.ConfigureWsFederationAuthentication(serviceProvider, authenticationSettings, authenticateEveryRequest);
}
private static IAppBuilder ConfigureWsFederationAuthentication(
this IAppBuilder app,
IServiceProvider serviceProvider,
WsFederationAuthenticationSettings authenticationSettings,
bool authenticateEveryRequest = true)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions
{
SlidingExpiration = authenticationSettings.UseCookieSlidingExpiration,
ExpireTimeSpan = authenticationSettings.GetCookieExpireTimeSpan()
});
var wsFederationAuthenticationOptions = GetWsFederationAuthenticationOptions(authenticationSettings);
app.UseWsFederationAuthentication(wsFederationAuthenticationOptions);
var eycAuthenticationManager = (IEycAuthenticationManager)serviceProvider.GetService(typeof(IEycAuthenticationManager));
app.Use<EycAuthenticationOwinMiddleware>(eycAuthenticationManager);
// http://stackoverflow.com/questions/23524318/require-authentication-for-all-requests-to-an-owin-application
if (authenticateEveryRequest)
{
app.Use(async (owinContext, next) =>
{
var user = owinContext.Authentication.User;
if (!(user?.Identity?.IsAuthenticated ?? false))
{
owinContext.Authentication.Challenge();
return;
}
await next();
});
}
return app;
}
private static WsFederationAuthenticationOptions GetWsFederationAuthenticationOptions(WsFederationAuthenticationSettings settings)
{
var wsFederationAuthenticationNotifications = GetWsFederationAuthenticationNotifications(settings);
var wsFederationAuthenticationOptions = new WsFederationAuthenticationOptions
{
Wtrealm = settings.Realm,
MetadataAddress = settings.MetadataAddress,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudiences = settings.Realms
},
Notifications = wsFederationAuthenticationNotifications
};
if (settings.UseCookieSlidingExpiration)
{
// this needs to be false for sliding expiration to work
wsFederationAuthenticationOptions.UseTokenLifetime = false;
}
return wsFederationAuthenticationOptions;
}
private static WsFederationAuthenticationNotifications GetWsFederationAuthenticationNotifications(WsFederationAuthenticationSettings settings)
{
var wsFederationAuthenticationNotifications = new WsFederationAuthenticationNotifications();
wsFederationAuthenticationNotifications.AuthenticationFailed = settings.AuthenticationFailed ?? wsFederationAuthenticationNotifications.AuthenticationFailed;
wsFederationAuthenticationNotifications.MessageReceived = settings.MessageReceived ?? wsFederationAuthenticationNotifications.MessageReceived;
wsFederationAuthenticationNotifications.RedirectToIdentityProvider = settings.RedirectToIdentityProvider ?? wsFederationAuthenticationNotifications.RedirectToIdentityProvider;
wsFederationAuthenticationNotifications.SecurityTokenReceived = settings.SecurityTokenReceived ?? wsFederationAuthenticationNotifications.SecurityTokenReceived;
wsFederationAuthenticationNotifications.SecurityTokenValidated = settings.SecurityTokenValidated ?? wsFederationAuthenticationNotifications.SecurityTokenValidated;
return wsFederationAuthenticationNotifications;
}
}
public class EycAuthenticationOwinMiddleware : OwinMiddleware
{
private readonly IEycAuthenticationManager _eycAuthenticationManager;
#region ctors
public EycAuthenticationOwinMiddleware(OwinMiddleware next, IEycAuthenticationManager eycAuthenticationManager)
: base(next)
{
if (eycAuthenticationManager == null)
{
throw new ArgumentNullException(nameof(eycAuthenticationManager));
}
this._eycAuthenticationManager = eycAuthenticationManager;
}
#endregion
public override Task Invoke(IOwinContext context)
{
if (context.Authentication.User != null)
{
context.Authentication.User =
this._eycAuthenticationManager.Authenticate(
context.Request.Uri.AbsoluteUri,
context.Authentication.User);
}
return this.Next.Invoke(context);
}
}
public class EycAuthenticationManager : ClaimsAuthenticationManager, IEycAuthenticationManager
{
private readonly IClaimsTransformer _claimsTransformer;
#region ctors
public EycAuthenticationManager(IClaimsTransformer claimsTransformer)
{
this._claimsTransformer = claimsTransformer;
}
#endregion
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (incomingPrincipal != null && !incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
return this._claimsTransformer.TransformIdentity(incomingPrincipal);
}
}
public class ClaimsTransformer : IClaimsTransformer
{
public ClaimsPrincipal TransformIdentity(IPrincipal principal)
{
if (!(principal is ClaimsPrincipal))
{
throw new Exception("The provided IPrincipal object is not of type ClaimsPrincipal.");
}
var user = (ClaimsPrincipal)principal;
var claims = user.Claims.ToList();
if (claims.All(x => x.Type != ClaimTypes.Email))
{
var upnClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Upn);
if (upnClaim != null)
{
claims.Add(new Claim(ClaimTypes.Email, upnClaim.Value));
}
}
return new ClaimsPrincipal(new ClaimsIdentity(claims, principal.Identity.AuthenticationType));
}
}
Here is the way how to SignOut using Owin context, app is "IAppBuilder":
app.Map("/signout", map =>
{
map.Run(ctx =>
{
ctx.Authentication.SignOut();
return Task.CompletedTask;
});
});
More details here: https://leastprivilege.com/2014/02/21/test-driving-the-ws-federation-authentication-middleware-for-katana/
UseWsFederationAuthentication will not work in AspNetCore MVC 1.0.0. UseWsFederationAuthentication used non-standard OWIN keys that are not supported by UseOwin, so it cannot communicate with MVC.
I'm using ASP.NET Web API 2 with attribute routing but i can't seem to get the versioning using media types application/vnd.company[.version].param[+json] to work.
I get the following error:
The given key was not present in the dictionary.
which originates from testing the key _actionParameterNames[descriptor] in FindActionMatchRequiredRouteAndQueryParameters() method.
foreach (var candidate in candidatesFound)
{
HttpActionDescriptor descriptor = candidate.ActionDescriptor;
if (IsSubset(_actionParameterNames[descriptor], candidate.CombinedParameterNames))
{
matches.Add(candidate);
}
}
Source: ApiControllerActionSelector.cs
After further debugging I've realized that if you have two controllers
[RoutePrefix("api/people")]
public class PeopleController : BaseApiController
{
[Route("")]
public HttpResponseMessage GetPeople()
{
}
[Route("identifier/{id}")]
public HttpResponseMessage GetPersonById()
{
}
}
[RoutePrefix("api/people")]
public class PeopleV2Controller : BaseApiController
{
[Route("")]
public HttpResponseMessage GetPeople()
{
}
[Route("identifier/{id}")]
public HttpResponseMessage GetPersonById()
{
}
}
you can't use your custom ApiVersioningSelector : DefaultHttpControllerSelector because it will test the keys,as stated above, from all controllers having the same [RoutePrefix("api/people")] and obviously an exception will be thrown.
Just to be sure the right controller was selected
I don't know if this is a bug, but using route [RoutePrefix("api/v1/people")] to version API makes me sad.
NOTE: This works great without attribute routing.
UPDATE
public class ApiVersioningSelector : DefaultHttpControllerSelector
{
private HttpConfiguration _HttpConfiguration;
public ApiVersioningSelector(HttpConfiguration httpConfiguration)
: base(httpConfiguration)
{
_HttpConfiguration = httpConfiguration;
}
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
IDictionary<string, HttpControllerDescriptor> controllers = GetControllerMapping();
var attributedRoutesData = request.GetRouteData().GetSubRoutes();
var subRouteData = attributedRoutesData.LastOrDefault(); //LastOrDefault() will get PeopleController, FirstOrDefault will get People{version}Controller which we don't want
var actions = (ReflectedHttpActionDescriptor[])subRouteData.Route.DataTokens["actions"];
var controllerName = actions[0].ControllerDescriptor.ControllerName;
//For controller name without attribute routing
//var controllerName = (string)routeData.Values["controller"];
HttpControllerDescriptor oldControllerDescriptor;
if (controllers.TryGetValue(controllerName, out oldControllerDescriptor))
{
var apiVersion = GetVersionFromMediaType(request);
var newControllerName = String.Concat(controllerName, "V", apiVersion);
HttpControllerDescriptor newControllerDescriptor;
if (controllers.TryGetValue(newControllerName, out newControllerDescriptor))
{
return newControllerDescriptor;
}
return oldControllerDescriptor;
}
return null;
}
private string GetVersionFromMediaType(HttpRequestMessage request)
{
var acceptHeader = request.Headers.Accept;
var regularExpression = new Regex(#"application\/vnd\.mycompany\.([a-z]+)\.v([0-9]+)\+json",
RegexOptions.IgnoreCase);
foreach (var mime in acceptHeader)
{
var match = regularExpression.Match(mime.MediaType);
if (match != null)
{
return match.Groups[2].Value;
}
}
return "1";
}
}
Thanks for the sharing your code. I have modified your version controller selector like below and tried some scenarios and it seems to work well. Can you try updating your controller selector like below and see if it works?
public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
{
HttpControllerDescriptor controllerDescriptor = null;
// get list of all controllers provided by the default selector
IDictionary<string, HttpControllerDescriptor> controllers = GetControllerMapping();
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
//check if this route is actually an attribute route
IEnumerable<IHttpRouteData> attributeSubRoutes = routeData.GetSubRoutes();
var apiVersion = GetVersionFromMediaType(request);
if (attributeSubRoutes == null)
{
string controllerName = GetRouteVariable<string>(routeData, "controller");
if (controllerName == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
string newControllerName = String.Concat(controllerName, "V", apiVersion);
if (controllers.TryGetValue(newControllerName, out controllerDescriptor))
{
return controllerDescriptor;
}
else
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
else
{
// we want to find all controller descriptors whose controller type names end with
// the following suffix(ex: CustomersV1)
string newControllerNameSuffix = String.Concat("V", apiVersion);
IEnumerable<IHttpRouteData> filteredSubRoutes = attributeSubRoutes.Where(attrRouteData =>
{
HttpControllerDescriptor currentDescriptor = GetControllerDescriptor(attrRouteData);
bool match = currentDescriptor.ControllerName.EndsWith(newControllerNameSuffix);
if (match && (controllerDescriptor == null))
{
controllerDescriptor = currentDescriptor;
}
return match;
});
routeData.Values["MS_SubRoutes"] = filteredSubRoutes.ToArray();
}
return controllerDescriptor;
}
private HttpControllerDescriptor GetControllerDescriptor(IHttpRouteData routeData)
{
return ((HttpActionDescriptor[])routeData.Route.DataTokens["actions"]).First().ControllerDescriptor;
}
// Get a value from the route data, if present.
private static T GetRouteVariable<T>(IHttpRouteData routeData, string name)
{
object result = null;
if (routeData.Values.TryGetValue(name, out result))
{
return (T)result;
}
return default(T);
}
In my apicontroller I use base.user to identify the authenticated user to use in a lookup. Now I am writing a unit test for this but I cannot figure out how to mock apicontroller.user. Do I need to create a request and set the user there? Or is there another way to set the controller.user?
Here is my controller; I have already mocked repository and membershipservice.
[Authorize]
public class DocumentController : ApiController
{
DocumentRepository _repository;
IStaticMembershipService _membership;
public IEnumerable<Document> GetDocuments()
{
MembershipUser userAccount = _membership.GetUser(base.User);
IEnumerable<Document> docs = null;
if (userAccount != null)
{
docs = _repository.GetDocumentsByUserId(
(Guid) userAccount.ProviderUserKey);
}
return docs;
}
Here is my unit test:
[TestClass]
public class DocumentControllerWebService
{
private DocumentsContext _context;
private DocumentRepository _repository;
private DocumentController _controller;
private FakeMembershipService _membership;
private TestContext testContextInstance;
[TestInitialize]
public void MyTestInitialize()
{
// Create a context with a fake data set provider
_context = new DocumentsContext(new FakeDbSetProvider());
_repository = new DocumentRepository(_context);
_membership = new FakeMembershipService();
_controller = new DocumentController(_repository, _membership);
}
public void GetDocumentsTest()
{
string userName = "someUser";
MembershipUser userAccount = _membership.GetUser(userName);
Guid userId = (Guid) userAccount.ProviderUserKey;
Guid anotherUserId = Guid.NewGuid();
// Get some dummy data and insert it into the fake repository
List<Document> forms = DocumentDummyData.GetListOfDummyData(
userId, anotherUserId);
forms.ForEach(f => _repository.InsertDocument(f));
// I would like to do this but User is readonly
_controller.User = userName;
List<Document> docs = _controller.GetDocuments().ToList();
foreach (Document expected in forms.Where(d => d.UserId == userId))
{
Document actual = docs.Where(
d => d.DocumentID == expected.DocumentID).FirstOrDefault();
Assert.IsNotNull(actual);
Assert.AreEqual(expected.DocumentID, actual.DocumentID);
}
}
}
If you are getting the user from http Request then you'll want to look at a way of mocking that out. Thankfully that has been done many times. A good place to start would be to read this
http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx
To summarize what I did which followed this, a hanselman blog and some trial and error:
In your ApiController add this to your constructor
HttpContextWrapper = HttpContextFactory.GetHttpContext();
The factory is this
public static class HttpContextFactory
{
[ThreadStatic]
private static HttpContextBase _mockHttpContext;
public static void SetHttpContext(HttpContextBase httpContextBase)
{
_mockHttpContext = httpContextBase;
}
public static HttpContextBase GetHttpContext()
{
if (_mockHttpContext != null)
{
return _mockHttpContext;
}
if (HttpContext.Current != null)
{
return new HttpContextWrapper(HttpContext.Current);
}
return null;
}
}
Now you have a seam into which you can insert your mock request, response, session, etc.
HttpContextBase httpContext = HttpMocks.HttpContext();
HttpContextFactory.SetHttpContext(httpContext);
Finally here is a fairly fully mocked context that I use
public class HttpMocks
{
public static HttpContextBase HttpContext()
{
var context = MockRepository.GenerateMock<HttpContextBase>();
context.Stub(r => r.Request).Return(HttpRequest());
context.Stub(r => r.Response).Return(HttpResponse());
context.Stub(r => r.Session).Return(HttpSession());
context.Stub(r => r.Server).Return(HttpServer());
return context;
}
private static HttpServerUtilityBase HttpServer()
{
var httpServer = MockRepository.GenerateMock<HttpServerUtilityBase>();
httpServer.Stub(r => r.MapPath("")).IgnoreArguments().Return("");
return httpServer;
}
private static HttpResponseBase HttpResponse()
{
var httpResponse = MockRepository.GenerateMock<HttpResponseBase>();
var cookies = new HttpCookieCollection {new HttpCookie("UserContext")};
httpResponse.Stub(r => r.Cookies).Return(cookies);
Func<string, string> returnWhatWasPassed = x => x;
httpResponse.Stub(r => r.ApplyAppPathModifier(""))
.IgnoreArguments().Do(returnWhatWasPassed);
return httpResponse;
}
public static HttpRequestBase HttpRequest()
{
var httpRequest = MockRepository.GenerateMock<HttpRequestBase>();
var cookies = new HttpCookieCollection
{
new HttpCookie("UserContext")
};
httpRequest.Stub(r => r.Cookies).Return(cookies);
var parameters = new NameValueCollection
{
{ "id", "277" },
{ "binderId", "277" }
};
httpRequest.Stub(r => r.Params).Return(parameters);
httpRequest.Stub(r => r.ApplicationPath).Return("/");
httpRequest.Stub(r => r.AppRelativeCurrentExecutionFilePath)
.Return("~/");
httpRequest.Stub(r => r.PathInfo).Return("");
var serverVariables = new NameValueCollection();
httpRequest.Stub(r => r.ServerVariables).Return(serverVariables);
return httpRequest;
}
public static HttpSessionStateBase HttpSession()
{
var s = new FakeSessionState();
s["mocking"] = "true";
return s;
}
}
this makes for a rather long answer but let us know if you need more detail on anything, you can probably ignore fake session for now.