Authenticated user is lost in web api owin middleware - c#

I'm using owin middleware and Jwt Bearer Aurhentication alongside Autofac that help my Webapi to handle requests.
JwtBearerAuthentication middleware works fine and set HttpContext.Current.User.Identity.IsAuthenticated to true and it persist until pipeline reaches to webapi middleware , in my webapi authenticated user is lost
order of middlewares are as follows:
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
#region Autofac config
var container = AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
#endregion
#region RoutConfig
RouteConfig.RegisterRoutes(RouteTable.Routes);
#endregion
//Register middlewares
app.UseAutofacMiddleware(container);
app.UseAutofacWebApi(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseJwtBearerAuthentication(new MyJwtAuthenticationOptions());
app.Use<RedirectUnAuthenticateRequestsMiddleware>();
app.Use<ReadBodyMiddleware>();
app.UseWebApi(config); //in this middleware authenticated user is lost
}
Here is my WebApiConfig class:
public static void Register(HttpConfiguration config)
{
// Owin auth
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter("Signature"));
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.Always;
// Web API routes
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
config.MapHttpAttributeRoutes();
config.Services.Insert(typeof(ModelBinderProvider), 0,
new SimpleModelBinderProvider(typeof(DocumentModel), new FromFormDataBinding()));
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Have you any idea?
Update:
Inside my owin middleware after authentication middleware, IsAuthenticated is set to true
public override async Task Invoke(IOwinContext context)
{
var isAuth=context.Request.User.Identity.IsAuthenticated;//It is true as expected.
await Next.Invoke(context);
return;
}
but when it reaches to my controller
HttpContext.Current.User.Identity.IsAuthenticated;//It is false.

Problem was from this line in WebApiConfig class;
config.SuppressDefaultHostAuthentication();
When i commented,issue disappeared and authenticated user persisted in webapi.

Related

Can't integrate autofac with both web api 2 and mvc

this thing takes one week from me
i have done many methods to find a solution
mvc fully integrated with autofac, but web api NO and NO! :-(
here is my codes:
AutofacDi
public static class AutofacDi
{
public static ValueTuple<IContainer, HttpConfiguration> Initialize()
{
var assembly = Assembly.GetExecutingAssembly();
var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;
builder.RegisterControllers(assembly);
builder.RegisterApiControllers(assembly).PropertiesAutowired();
builder.RegisterHttpRequestMessage(config);
builder.RegisterAssemblyModules(assembly);
builder.RegisterAssemblyTypes(assembly).PropertiesAutowired();
builder.RegisterFilterProvider();
builder.RegisterWebApiFilterProvider(config);
builder.RegisterModelBinders(assembly);
builder.RegisterWebApiModelBinderProvider();
builder.RegisterModelBinderProvider();
builder.RegisterModule<AutofacWebTypesModule>();
builder.RegisterSource(new ViewRegistrationSource());
builder.RegisterType<T4MVC.Dummy>().AsSelf();
builder.RegisterType<FoodDbContext>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.Register(context => (FoodDbContext)context.Resolve<IUnitOfWork>())
.As<FoodDbContext>()
.InstancePerLifetimeScope();
builder.RegisterType<ApplicationDbContext>().As<DbContext>().InstancePerLifetimeScope();
builder.RegisterType<UserStore<ApplicationUser>>().As<IUserStore<ApplicationUser>>();
builder.RegisterType<ApplicationUserManager>();
builder.RegisterType<ApplicationSignInManager>();
builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager>()
{
DataProtectionProvider = new DpapiDataProtectionProvider("FoodBaMa")
});
builder.Register(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerLifetimeScope();
builder.RegisterType<RoleStore<IdentityRole>>().As<IRoleStore<IdentityRole, string>>();
builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly)
.Where(t => t.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
return new ValueTuple<IContainer, HttpConfiguration>(container, config);
}
}
OWIN Startup
[assembly: OwinStartup(typeof(FoodBaMa.Startup))]
namespace FoodBaMa
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
var iOc = AutofacDi.Initialize();
app.UseAutofacMiddleware(iOc.Item1);
app.UseAutofacMvc();
app.UseWebApi(iOc.Item2);
app.UseAutofacWebApi(iOc.Item2);
WebApiConfig.Register(iOc.Item2);
app.UseCors(CorsOptions.AllowAll);
ConfigureAuth(app);
}
}
}
Global
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
ModelBinders.Binders.Add(typeof(string), new PersianModelBinder());
MvcHandler.DisableMvcResponseHeader = true;
DbInterception.Add(new ElmahEfInterceptor());
DbInterception.Add(new YeKeInterceptor());
GlobalConfiguration.Configuration.EnsureInitialized();
}
}
ApiController
[AutofacControllerConfiguration]
[WebApiCompress]
[RoutePrefix("api/v1")]
public class AppController : ApiController
{
private readonly IApiV1Service _apiService;
public AppController(
IApiV1Service apiService
)
{
_apiService = apiService;
}
[HttpPost]
[Route("app/mainview")]
public virtual async Task<IHttpActionResult> MainView([FromBody] Request model)
{
var Result = new Models.API.V1.App.MainView.Response { Status = CheckTokenEnum.Error };
try
{
if (ModelState.IsValid)
Result = await _apiService.MainView(model).ConfigureAwait(false);
}
catch (Exception ex)
{
ErrorLog.GetDefault(null).Log(new Error(ex));
}
return Json(Result, R8.Json.Setting);
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.JsonIntegration();
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
config.MessageHandlers.Add(new CachingHandler(new InMemoryCacheStore()));
config.MessageHandlers.Add(new PreflightRequestsHandler());
config.Filters.Add(new ElmahHandleErrorApiAttribute());
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//routes.IgnoreRoute("{*browserlink}", new { browserlink = #".*/arterySignalR/ping" });
routes.MapMvcAttributeRoutes();
AreaRegistration.RegisterAllAreas();
//routes.LowercaseUrls = true;
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new
{
controller = "Home",
action = "Index",
id = UrlParameter.Optional
},
namespaces: new[] { "FoodBaMa.Controllers" }
);
}
}
on each web api request, returns:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Module: IIS Web Core
Notification: MapRequestHandler
Handler: StaticFile
Error Code: 0x80070002
It's a killing problem for me because it's two weeks that making my website application unusable.
i don't know what to do.
help me !!!
i fixed that issue by commenting:
builder.RegisterWebApiFilterProvider(config);
and
builder.RegisterHttpRequestMessage(config);
in AutofacDi
It appears you may have gotten past your issue, which I hope is true. There's a lot to digest in here, but I do see a common mistake in the very start with respect to OWIN integration and Web API as documented in the Autofac docs:
A common error in OWIN integration is use of the GlobalConfiguration.Configuration. In OWIN you create the configuration from scratch. You should not reference GlobalConfiguration.Configuration anywhere when using the OWIN integration.
You may run into additional/other challenges in your setup as it sits; if you do, try getting rid of the use of GlobalConfiguration.Configuration.

OAuth Bearer Token Not Working for WebApi

I have gone through a lot of docs but it seems my problem is strange.
I have configured Oauth but I am not able to get the bearer token back. whenever I hit api to get the token, I get 200 but nothing back in response(I am expecting bearer token). Below is the config:
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions oAuthOptions = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
Provider = new ApplicationOAuthProvider()
};
app.UseOAuthAuthorizationServer(oAuthOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new OAuthBearerAuthenticationProvider()
});
HttpConfiguration config = new HttpConfiguration();
//config.Filters.Add(new );
//config.MapHttpAttributeRoutes();
// There can be multiple exception loggers. (By default, no exception loggers are registered.)
//config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
WebApiConfig.Register(config);
//enable cors origin requests
app.UseCors(CorsOptions.AllowAll);
app.UseWebApi(config);
}
}
public static class WebApiConfig
{
/// <summary>
///
/// </summary>
/// <param name="config"></param>
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Filters.Add(new HostAuthenticationAttribute("bearer")); //added this
config.Filters.Add(new AuthorizeAttribute());
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var form = await context.Request.ReadFormAsync();
if (myvalidationexpression)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Role, "AuthorizedUser"));
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "Provided username and password is incorrect");
}
}
}
Now when I launch the APi and hit /token, I get this as below:
API Request
I think that code you have written in WebApiConfig.cs to suppress host authentication and some other code is creating the issue.
I have a working example for bearer token generation in web API, which is working properly and generating token.
WebApiConfig.cs file code:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Startup.cs Code:
[assembly: OwinStartup(typeof(WebAPI.Startup))]
namespace WebAPI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions
OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60),
Provider=new ApplicationOAuthProvider(),
//AuthenticationMode = AuthenticationMode.Active
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
Provider = new OAuthBearerAuthenticationProvider()
}
);
}
}
}
Controller to check authorization call after adding bearer token in the request.
public class TokenTestController : ApiController
{
[Authorize]
public IHttpActionResult Authorize()
{
return Ok("Authorized");
}
}
install the following package
Microsoft.Owin.Host.SystemWeb

Cors does not work on Asp.Net Web Api

I tried solutions I found here in stackoverflow and other sites, but they did not solve my issue.
So what I did first is to install the Owin.Cors package and remove the AspNet.WebApi.Cors to see it that the only thing I need to enable CORS to our Web Api and OAuth. It does work in OAuth but not in the Web Api. As the suggestion that to make it work it should be initiliaze first before any configuration so I did this, see the below code.
public void ConfigureAuth(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/login"),
Provider = new CookieAuthenticationProvider
{
// remove for brevity
},
ExpireTimeSpan = TimeSpan.FromMinutes(Settings.Instance.SessionExpiryTimeout)
});
DataProtectionProvider = app.GetDataProtectionProvider();
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
// remove content for brevity
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
When I'm doing a request to retrieve a token I'm getting this:
"Access-Control-Allow-Origin": "*"
"Access-Control-Allow-Credentials": "true"
However when I'm calling to an Api and I assume that the response header would include the above but it didn't. Thus cause an exception: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:44320' is therefore not allowed access. The response had HTTP status code 404.
I also tried to add again the AspNet.WebApi.Cors but this does not work. Would it be because of our configuration, we are using Autofac. See the below code:
WebApiConfig
public class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "GET,POST");
config.EnableCors(cors);
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
var jsonpFormatter = new JsonpMediaTypeFormatter(config.Formatters.JsonFormatter);
config.Formatters.Add(jsonpFormatter);
config.Routes.MapHttpRoute(
"ApiDefault",
"api/{controller}/{id}",
new {id = RouteParameter.Optional}
);
}
}
DependencyConfig
public class DependencyConfig
{
public static void Register()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// omitted some codes
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
}
Global.asax
protected void Application_Start()
{
XmlConfigurator.Configure();
MvcHandler.DisableMvcResponseHeader = true;
// omitted some codes
WebApiConfig.Register(GlobalConfiguration.Configuration);
// omitted some codes
DependencyConfig.Register();
JsonConfig.Configure();
}
Any idea what causing the problem? Thank you.

Web API 2 DelegateHandler Not Invoked When IdentityServer3 Implemented

I am having a very weird scenario when trying to add a custom DelegatingHandler. The SendAsync gets invoked. Up to this point, everything is happy with life.
However, as soon as I add Authentication using IdentityServer3, all of my DelegatingHandlers are ignored. SendAsync() is not invoked.
The DelegatingHandler:
public class LogRequestAndResponseHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// log request body
string requestBody = await request.Content.ReadAsStringAsync();
//Trace.WriteLine(requestBody);
// let other handlers process the request
var result = await base.SendAsync(request, cancellationToken);
// once response body is ready, log it
var responseBody = await result.Content.ReadAsStringAsync();
//Trace.WriteLine(responseBody);
return result;
}
}
The startup.cs
public void Configuration(IAppBuilder app)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = Globals.TokenAuthenticationAuthority,
ValidationMode = ValidationMode.ValidationEndpoint,
RequiredScopes = new[] { "scope1", "scope2", "scope3" }
});
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Filters.Add(new AuthorizeAttribute());
app.UseWebApi(config);
}
The WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MessageHandlers.Add(new LogRequestAndResponseHandler());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
After digging and playing around, I found that the line that breaks is the
config.MapHttpAttributeRoutes();
But I just dont understand why. Any help will be much appreciated.
From the comment chain on the question
Configuration() gets called after 'WebApiConfig.Register()'
This is the problem. The Configuration() method in Startup.cs creates a new HttpConfiguration and passes it to .UseWebApi(). This effectively undoes everything that WebApiConfig.Register() does, as it adds filters, message handlers, etc. to the HttpConfiguration that is passed in.
To fix this, you have two options:
Change var config = new HttpConfiguration(); in Startup.cs to var config = GlobalConfiguration.Configuration
Call Startup.Configuration() before WebApiConfig.Register() and be sure to pass in the new HttpConfiguration

C# WebApi DI not working

Hello i need some assistance. I'm struggling on this second day and can't find a source of the problem. I'm working on web api with token authorization , identity and ninject.
This is my kernel :
public IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<AppContext>().ToSelf().InRequestScope();
kernel.Bind(x => { x.From(typeof(UserService).Assembly).SelectAllClasses().EndingWith("Service").BindDefaultInterface(); });
kernel.Bind(typeof(IUserStore<AppIdentityUser>)).To(typeof(UserStore<AppIdentityUser>)).InRequestScope()
.WithConstructorArgument("context", kernel.Get<AppContext>());
kernel.Bind(typeof(UserManager<AppIdentityUser>)).To(typeof(UserManager<AppIdentityUser>)).InRequestScope()
.WithConstructorArgument("store", kernel.Get<IUserStore<AppIdentityUser>>());
kernel.Bind(typeof(IRoleStore<IdentityRole, string>)).To(typeof(RoleStore<IdentityRole>)).InRequestScope().WithConstructorArgument("context", kernel.Get<AppContext>());
kernel.Bind(typeof(RoleManager<IdentityRole>)).To(typeof(RoleManager<IdentityRole>)).InRequestScope().WithConstructorArgument("store", kernel.Get<IRoleStore<IdentityRole, string>>());
kernel.Bind<IOAuthAuthorizationServerProvider>().To<AuthorizationServerProvider>();
kernel.Bind<IOAuthAuthorizationServerOptions>().To<MyOAuthAuthorizationServerOptions>();
return kernel;
}
This is my api controller :
public UsersController(IUserService userService)
{
this._userService = userService;
}
public IHttpActionResult Login()
{
//get user method
}
this is my service :
public UserService(UserManager<AppIdentityUser> userMenager, RoleManager<IdentityRole> roleManager)
{
this._userMenager = userMenager;
this._roleManager = roleManager;
}
public AppIdentityUser GetUser(string name, string password)
{
return _userMenager.Find(name, password); // here I recive error on second time
}
Problem is that this works only once. When i open application and perform one get action it works on the second time when i try after few seconds i get exception that Context in user Store is disposed. I suspect that it's problem with my ninject configuration but don't see any error.
Edit: this is my Owin Startup Class
public void Configuration(IAppBuilder app)
{
config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
var kernel = ConfigureNinject(app);
ConfigureOAuth(app, kernel);
config.DependencyResolver = new NinjectResolver(kernel);
//app.UseWebApi(config);
app.UseNinjectMiddleware(() => kernel);
app.UseNinjectWebApi(config);
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AutoMapperConfiguration.Configure();
}
public void ConfigureOAuth(IAppBuilder app, IKernel kernel)
{
app.UseOAuthBearerTokens(kernel.Get<IOAuthAuthorizationServerOptions>().GetOptions());
}

Categories

Resources