IOwinContext.Get<DbContext>() returns null - c#

I am trying to add authentication to add authentication to an existing MVC 5 application I started from an empty project. I started a new WebAPI project with individual user accounts so I could see how it was configured. I copied over the code having to do with authentication and refactored the namespaces and class names. In the code below, the first line var identityContext = context.Get<IdentityDbContext>() returns null and causes the second line var userStore = new UserStore<AdminAppUser>(identityContext) to throw an error due to a null parameter.
I probably didn't include enough code, as I am very new to MVC Authentication and have a poor understanding of how all the pieces fit together. if I need to include more code please let me know which pieces would be useful. Thank you!
public static AdminAppUserManager Create(IdentityFactoryOptions<AdminAppUserManager> options, IOwinContext context)
{
var identityContext = context.Get<IdentityDbContext>();
var userStore = new UserStore<AdminAppUser>(identityContext);
var manager = new AdminAppUserManager(userStore);
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<AdminAppUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<AdminAppUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
EDIT:
startup.auth.cs
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(AdminAppIdentityDbContext.Create);
app.CreatePerOwinContext<AdminAppUserManager>(AdminAppUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
startup.cs:
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
Edit 2:
public class AdminAppIdentityDbContext : IdentityDbContext<AdminAppUser>
{
public AdminAppIdentityDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static AdminAppIdentityDbContext Create()
{
return new AdminAppIdentityDbContext();
}
}

There should be some sort of ConfigureAuth method that gets called at startup to establish that there is one IdentityDbContext per Owin context. That call will look like:
app.CreatePerOwinContext(IdentityDbContext.Create);
That call should be in the boilerplate that VS generates automatically for you.

You could also just replace
var identityContext = context.Get<IdentityDbContext> with
var identityContext = new AdminAppIdentityDbContext();,
it doesn't really matter. It may spare your time.

Related

Session value will lost asp.net mvc

I have an asp.net MVC and webapi2 application.I want to set OrderId in session and send User to bank website to pay the order and when the bank website will return him to my callback URL in my website I want to get OrderId from the session but it seems that is null. I want to know why it happens?
and another problem is that I use cookie authentication in identity but it doesn't work too. I have set it to 15 days .but it doesn't work too.I don't know but maybe these two problems are related to each other.if someone knows
Why my asp.net identity -user will log out automatically
public ActionResult Pay()
{
Session["orderid"]=12;
}
//callbackurl
public ActionResult Result()
{
var orderid=Convert.ToInt32( Session["orderid"]);//is null
}
the below is in my web.config
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/User/Login" timeout="30">
</forms>
</authentication>
<sessionState timeout="30"></sessionState>
</system.web>
and the below is in startup.cs file
public class Startup
{
public string Issuer { get; set; }
public void Configuration(IAppBuilder app)
{
Issuer = "http://mywebsite.ir/";
ConfigureOAuthTokenGeneration(app);
ConfigureOAuthTokenConsumption(app);
app.UseCors(CorsOptions.AllowAll);
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
//app.UseWebApi(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
//app.UseMvc(RouteConfig.RegisterRoutes);
//ConfigureWebApi(GlobalConfiguration.Configuration);
}
private void ConfigureOAuthTokenGeneration(IAppBuilder app)
{
app.CreatePerOwinContext(() => new LeitnerContext());
app.CreatePerOwinContext<LeitnerUserManager>(LeitnerUserManager.Create);
app.CreatePerOwinContext<LeitnerRoleManager>(LeitnerRoleManager.Create);
// Plugin the OAuth bearer JSON Web Token tokens generation and Consumption will be here
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new Microsoft.Owin.PathString("/User/Login"),
ExpireTimeSpan = TimeSpan.FromDays(15),
Provider = new CookieAuthenticationProvider
{
OnApplyRedirect = ctx =>
{
if (!IsForApi(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
});
OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/api/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(15),
Provider = new LeitnerOAuthProvider(),
AccessTokenFormat = new LeitnerJwtFormat(Issuer),
};
app.UseOAuthAuthorizationServer(options);
//app.UseJwtBearerAuthentication(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
//app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
private bool IsForApi(IOwinRequest request)
{
IHeaderDictionary headers = request.Headers;
return ((headers != null) && ((headers["Accept"] == "application/json") || (request.Path.StartsWithSegments(new PathString("/api")))));
}
private void ConfigureOAuthTokenConsumption(IAppBuilder app)
{
var a = AudiencesStore.AudiencesList["LeitnerAudience"];
string audienceId = a.ClientId;// ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode(a.Base64Secret/*ConfigurationManager.AppSettings["as:AudienceSecret"]*/);
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(Issuer, audienceSecret)
}
});
}
}
Edit
My WebHost is Plesk Onyx,In the Hosting Setting I see a setting Preferred domain that have three item to select
1- www.jooyabash.ir
2- jooyabash.ir
3- None
Description :Select the URL (either with or without the www. prefix) to which site visitors will be redirected via a SEO-safe HTTP 301 redirect.
When I set it to 1 or 3 i see that session will lost.but when i set it to 2 session until 10 min it will not lost and the payment will compelet in this time
Does any one know why?

ASP.NET MVC: No IUserTokenProvider is registered using Ninject

I am running into the error No IUserTokenProvider is registered on a call to _userManager.GenerateEmailConfirmationTokenAsync(user.Id); which is generating a token to be sent in an account registration e-mail. I have reviewed many posts related to this and none have solved my issue. From what I've learned, this functionality is hooked up in the ApplicationUserManager class by the following:
if (dataProtectionProvider != null)
{
IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}
I've attempted to resolve the issue by doing the following as suggested elsewhere: My ApplicationUserManager class has teh following signature:
public ApplicationUserManager(IUserStore<ApplicationUser> store, IDataProtectionProvider dataProtectionProvider)
and the dataProtectionProvider I am injecting is bound by Ninject in Startup.cs like this:
private IAppBuilder _app;
public void Configuration(IAppBuilder app)
{
_app = app;
ConfigureAuth(app);
app.UseNinjectMiddleware(CreateKernel);
}
private IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
//bindings
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
kernel.Bind<DbContext>().To<MvcIndividualAuthContext>().InRequestScope();
kernel.Bind(typeof(IUserStore<>)).To(typeof(UserStore<>)).InRequestScope();
kernel.Load(Assembly.GetExecutingAssembly());
kernel.Bind<MvcIndividualAuthContext>().ToSelf().InRequestScope();
kernel.Bind<IUserStore<ApplicationUser, string>>().To<ApplicationUserStore>();
kernel.Bind<ApplicationUserManager>().ToSelf();
kernel.Bind<ApplicationSignInManager>().ToSelf();
kernel.Bind<IAuthenticationManager>().ToMethod(x => HttpContext.Current.GetOwinContext().Authentication);
kernel.Bind<IdentityFactoryOptions<ApplicationUserManager>>().ToSelf();
//this bind should be binding the IDataProtectionProvider for my
//ApplicationUserManager
kernel.Bind<IDataProtectionProvider>().ToMethod(x => _app.GetDataProtectionProvider());
return kernel;
}
however the binding doesn't seem to be working because my ApplicationUserManager's UserTokenProvider is still null at the time of generating my token. For reference, you can find the code for my ApplicationUserManager below:
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IDataProtectionProvider dataProtectionProvider)
: base(store)
{
// Configure validation logic for usernames
this.UserValidator = new UserValidator<ApplicationUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
this.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
this.UserLockoutEnabledByDefault = true;
this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
this.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
this.EmailService = new EmailService();
this.SmsService = new SmsService();
if (dataProtectionProvider != null)
{
IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtector);
}
}
}
All help is greatly appreciated.
After cleaning and building the solution, the issue has been resolved. Note that the solution had been built numerous times during while the issue was occurring but not cleaned.

c# web api owin authentication

I am very new to WebAPi Authentication even it seems OWIN being popular use. I dont understand why I should use EntityFramework for OWIN authentication as ApplicationDbContext is inhreting from IdentityDbContext and IdentityDbContext is in EntityFramework namespace. Below is procedure which is created automatically when we choose Individual User Accounts within WebApi project template:
public partial class Startup
{
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
public static string PublicClientId { get; private set; }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
//{
// ClientId = "",
// ClientSecret = ""
//});
}
}
Within ConfigureAuth procedure ApplicationDbContext is referenced.
Could you pls help me to write simple Authentication with OWIN and not to use EntityFramework?
Thanks.
you donĀ“t need to use EF, yes, the template uses EF and ASPNET Identity to do the authentication, but you can start using the black template and add it without EF, look the following part of code:
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new SimpleAuthorizationServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
SimpleAuthorizationServerProvider.cs
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
if (context.UserName != "Admin")
{
context.SetError("upps!", "Wrong data");
return;
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
Also, you can download a simple example here: http://1drv.ms/1mmaqtn
Regards,

No IUserTokenProvider is registered when using dependency injection

I got an error when my GeneratePasswordResetTokenAsync() method is call. I configured autofac with owin identity.
The error is :
No IUserTokenProvider is registered when using dependency injection
In my sample.web project there is a AutofacConfig.cs file where I register signinmanager and usermanager which I created in sample.repository project.
AutofacConfig.cs
public class AutofacConfig
{
public static Autofac.IContainer RegisterDependencies()
{
var containerBuilder = new ContainerBuilder();
// REGISTER DEPENDENCIES
containerBuilder.RegisterType<SampleDataContext>()
.As<DbContext>()
.InstancePerDependency();
containerBuilder.RegisterType<UserStore<SampleUser>>()
.As<IUserStore<SampleUser>>()
.InstancePerRequest();
containerBuilder.RegisterType<ApplicationUserManager>()
.AsSelf()
.InstancePerRequest();
containerBuilder.RegisterType<ApplicationSignInManager>()
.AsSelf()
.InstancePerRequest();
containerBuilder.RegisterType<EmailService>();
containerBuilder.Register<IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication)
.InstancePerRequest();
var container = containerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
var resolver = new AutofacWebApiDependencyResolver(container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
return container;
}
}
ApplicationUserManager.cs
public class ApplicationUserManager : UserManager<SampleUser>
{
public ApplicationUserManager(IUserStore<SampleUser> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<SampleUser>(context.Get<SampleDataContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<SampleUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 8,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<SampleUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<SampleUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var provider = new DpapiDataProtectionProvider("Sample");
manager.UserTokenProvider = new DataProtectorTokenProvider<SampleUser>(
provider.Create("ASP.NET Identity"));
return manager;
}
}
Remove create() method in ApplicationUserManager.cs class and add that code in ApplicationUserManager class's constructor.
ApplicationUserManager.cs
public class ApplicationUserManager : UserManager<SampleUser>
{
public ApplicationUserManager(IUserStore<SampleUser> store, IDataProtectionProvider dataProtectionProvider)
: base(store)
{
// Configure validation logic for usernames
this.UserValidator = new UserValidator<SampleUser>(this)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
this.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = false,
RequireDigit = false,
RequireLowercase = false,
RequireUppercase = false,
};
// Configure user lockout defaults
this.UserLockoutEnabledByDefault = true;
this.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
this.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
this.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<SampleUser>
{
MessageFormat = "Your security code is {0}"
});
this.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<SampleUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
this.EmailService = new EmailService();
this.SmsService = new SmsService();
// var dataProtectionProvider = Startup.DataProtectionProvider;
if (dataProtectionProvider != null)
{
IDataProtector dataProtector = dataProtectionProvider.Create("ASP.NET Identity");
this.UserTokenProvider = new DataProtectorTokenProvider<SampleUser>(dataProtector);
}
}
}
register DataProtectionProvider in AutofacConfig.cs file
containerBuilder.Register<IDataProtectionProvider>(c => Startup.DataProtectionProvider).InstancePerRequest();
Resolve ApplicationUSerManager class in Startup.cs class
public partial class Startup
{
public static IDataProtectionProvider DataProtectionProvider { get; private set; }
public void ConfigureAuth(IAppBuilder app)
{
// add this assignment
DataProtectionProvider = app.GetDataProtectionProvider();
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(SampleDataContext.Create);
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationUserManager>());
app.CreatePerOwinContext(() => DependencyResolver.Current.GetService<ApplicationSignInManager>());
}
}
just got solution from here
it is very helpful article

.Net OWIN WebApiConfig not being called

I created a blank project so I could create an angular application.
Now I have all that in place, I decided that I want to add Web API to this project. I installed all the required packages and set up the WebApiConfig.cs file.
Then I installed OWIN and created the OWIN Startup Class. When I run my project, the OWIN Startup Class is invoked properly, but the WebApiConfig is not.
In the past (pre-OWIN) using Global.asax was how you fired all your configuration classes, but because I am using OWIN the global.asax file is not needed and therefore I never created it.
Has someone come across this before and knows what I am doing wrong?
Update 1
I added a Global.asax page and it executed.
I was under the impression that if you use OWIN, you should delete your Global.asax file?
Here are both the Global.asax file
public class Global : HttpApplication
{
protected void Application_Start()
{
// Add these two lines to initialize Routes and Filters:
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
and the Startup.Config file.
public class StartupConfig
{
public static UserService<User> UserService { get; set; }
public static string PublicClientId { get; private set; }
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
static StartupConfig()
{
UserService = new UserService<User>(new UnitOfWork<DatabaseContext>(), false, true);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new OAuthProvider<User>(PublicClientId, UserService),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void Configuration(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "vnaJZLYwWFbv7GBlDeMbfwAlD",
// consumerSecret: "Q1FE1hEN6prXnK2O9TYihTFyOQmcQmrZJses0rT8Au4OsDQISQ");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
}
Update 2
My startup class looks like this now:
public class StartupConfig
{
public static UserService<User> UserService { get; set; }
public static string PublicClientId { get; private set; }
public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
static StartupConfig()
{
UserService = new UserService<User>(new UnitOfWork<DatabaseContext>(), false, true);
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new OAuthProvider<User>(PublicClientId, UserService),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
AllowInsecureHttp = true
};
}
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void Configuration(IAppBuilder app)
{
//var config = new HttpConfiguration();
//// Set up our configuration
//WebApiConfig.Register(config);
// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "vnaJZLYwWFbv7GBlDeMbfwAlD",
// consumerSecret: "Q1FE1hEN6prXnK2O9TYihTFyOQmcQmrZJses0rT8Au4OsDQISQ");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
//app.UseGoogleAuthentication();
}
}
If I uncomment the WebApiConfig line then the startup class is never executed.
Any idea why?
You'll need to call app.UseWebApi in your startup class, passing in the configuration you want to use. You'll also need to call your WebApiConfig's Register method there too. An example of how this might look in a cut down application is:
You could have an OWIN startup class that looks something like this:
// Tell OWIN to start with this
[assembly: OwinStartup(typeof(MyWebApi.Startup))]
namespace MyWebApi
{
public class Startup
{
/// <summary>
/// This method gets called automatically by OWIN when the application starts, it will pass in the IAppBuilder instance.
/// The WebApi is registered here and one of the built in shortcuts for using the WebApi is called to initialise it.
/// </summary>
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
}
The HttpConfiguration is created and passed to the WebApiConfig.Register method. We then use the app.UseWebApi(config) method to setup the web api. This is a helper method in System.Web.Http.Owin, you can get it by including the NuGet package Microsoft ASP.NET Web API 2.2 OWIN
The WebApiConfig class would look something like this:
namespace MyWebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Certainly, If you use Owin you may delete you Global.asax file.
In your Owin Startup.cs you have to put your WebApiConfig registration.
public class Startup
{
public void Configuration(IAppBuilder app)
{
...
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
config.Filters.Add(new WebApiAuthorizeAttribute());
...
}
...
}

Categories

Resources