public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext<IdentityUserManager>(IdentityUserManager.Create); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/OAuth/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(5), AllowInsecureHttp = true }; app.UseOAuthBearerTokens(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "852925537385-9t4d8fg869kpi1dlm58v77277b70lc6e.apps.googleusercontent.com", // ClientSecret = "078iMDZvE2JKYZc8-a5TeEey", // Provider = new GoogleAuthProvider() //}); }
public void ConfigureOAuth(IAppBuilder app) { //use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); //Configure Facebook External Login //FacebookAuthOptions = new FacebookAuthenticationOptions() //{ // AppId = "841670309262660", // AppSecret = "8b4eba3df30d4aa95427fa9c90372462", // Provider = new FacebookAuthProvider(), // Scope = { "user_about_me", "user_friends", "email", "read_friendlists", "publish_stream", "user_birthday", "user_location" } //}; //app.UseFacebookAuthentication(FacebookAuthOptions); }
private void ConfigureOAuth(IAppBuilder app) { app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider(new AccountRepository()) }; GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = "592613624399-a3gr6vveaocnptgvv6738rmnk0pb5cev.apps.googleusercontent.com", ClientSecret = "FqNKKib_BP7dsNYBoJa8NwUC", Provider = new GoogleAuthProvider() }; app.UseGoogleAuthentication(GoogleAuthOptions); FacebookAuthOptions = new FacebookAuthenticationOptions() { AppId = "806191272841558", AppSecret = "1a8241e9d46c4a5e393ae51f265a3489", Provider = new FacebookAuthProvider() }; app.UseFacebookAuthentication(FacebookAuthOptions); // Token Generation app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); }
private void ConfigureOAuth(IAppBuilder app) { //var serverOptions = new OAuthAuthorizationServerOptions() //{ // AuthenticationMode=Microsoft.Owin.Security.AuthenticationMode.Active, // AllowInsecureHttp = true, // TokenEndpointPath = new PathString("/token"), // AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), // Provider = new CIRAuthorizationServerProvider() //}; //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); var implicitGrantServerOptions = new OAuthAuthorizationServerOptions { AuthorizeEndpointPath= new PathString("/token"), Provider= new CIRImplicitAuthorizationServerProvider(), AllowInsecureHttp = true, AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(100) }; app.UseOAuthAuthorizationServer(implicitGrantServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationType="Bearer", AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active }); }
/// <summary> /// 初始化OAuth /// </summary> /// <param name="app"></param> /// <param name="provider"></param> /// <returns></returns> public static IAppBuilder ConfigureOAuth(this IAppBuilder app, IServiceProvider provider) { IOAuthAuthorizationServerProvider oauthServerProvider = provider.GetService<IOAuthAuthorizationServerProvider>(); if (oauthServerProvider == null) { throw new InvalidOperationException(Resources.OAuthServerProviderIsNull); } IAuthorizationCodeProvider authorizationCodeProvider = provider.GetService<IAuthorizationCodeProvider>(); if (authorizationCodeProvider == null) { throw new InvalidOperationException(Resources.AuthorizationCodeProviderIsNull); } IRefreshTokenProvider refreshTokenProvider = provider.GetService<IRefreshTokenProvider>(); if (refreshTokenProvider == null) { throw new InvalidOperationException(Resources.RefreshTokenProviderIsNull); } OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions() { TokenEndpointPath = new PathString("/token"), AuthorizeEndpointPath = new PathString("/authorize"), ApplicationCanDisplayErrors = true, AuthenticationMode = AuthenticationMode.Active, #if DEBUG AllowInsecureHttp = true, #endif Provider = oauthServerProvider, AuthorizationCodeProvider = authorizationCodeProvider, RefreshTokenProvider = refreshTokenProvider }; app.UseOAuthAuthorizationServer(options); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); return app; }
public static void Configuration(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); var OAuthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/oauth/Token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(8), Provider = new Providers.MyAuthorizationServerProvider(), // RefreshTokenProvider = new Providers.MyRefreshTokenProvider(DateTime.UtcNow.AddHours(8)) }; app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); // Configure Web API for self-host. HttpConfiguration config = new HttpConfiguration(); config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); // We don't need this crap anymore! //config.Routes.MapHttpRoute( // name: "DefaultApi", // routeTemplate: "api/{controller}/{id}", // defaults: new { id = RouteParameter.Optional } //); app.UseWebApi(config); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // app.CreatePerOwinContext<UserManager>(() => new UserManager(new UserStore())); // app.CreatePerOwinContext<Custom.Identity.RoleManager>(() => new Custom.Identity.RoleManager(new Custom.Identity.RoleStore())); //app.CreatePerOwinContext<SignInService>((options, context) => new SignInService(context.GetUserManager<UserManager>(), context.Authentication)); app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); var OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new Api.Socioboard.App_Start.ApplicationOAuthServerProvider("self"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // Only do this for demo!! AllowInsecureHttp = true }; // Token Generation app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); }
public void ConfigureAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AuthenticationType = Constant.GrantTypes.AuthenticationType, AllowInsecureHttp = true, TokenEndpointPath = new PathString(WebConfig.TokenPath), AccessTokenExpireTimeSpan = TimeSpan.FromSeconds(int.Parse(WebConfig.AccessTokenExpireTimeSpan)), Provider = new OAuth2AuthorizationServerProvider(), RefreshTokenProvider = new OAuth2RefreshTokenProvider() }; //AuthenticationType :认证类型 //AllowInsecureHttp : 如果允许客户端的 return_uri 参数不是 HTTPS 地址, 则设置为 true //TokenEndpointPath : 客户端应用可以直接访问并得到访问令牌的地址, 必须以前倒斜杠 "/" 开始, 例如: /Token //AccessTokenExpireTimeSpan :Token过期时间 //Provider : 应用程序提供和 OAuth 认证中间件交互的 IOAuthAuthorizationServerProvider 实例, 通常可以使用默认的 //OAuthAuthorizationServerProvider , 并设置委托函数即可 //RefreshTokenProvider :刷新令牌, 如果这个属性没有设置, 则不能从 /Token 刷新令牌 // 令牌生成 app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); //跨域处理 app.UseCors(CorsOptions.AllowAll); }
// Дополнительные сведения о настройке аутентификации см. по адресу: http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Настройка контекста базы данных и диспетчера пользователей для использования одного экземпляра на запрос app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); // Включение использования файла cookie, в котором приложение может хранить информацию для пользователя, выполнившего вход, // и использование файла cookie для временного хранения информации о входах пользователя с помощью стороннего поставщика входа app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Настройка приложения для потока обработки на основе OAuth PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // В рабочем режиме задайте AllowInsecureHttp = false AllowInsecureHttp = true }; // Включение использования приложением маркера-носителя для аутентификации пользователей app.UseOAuthBearerTokens(OAuthOptions); }
public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user and role manager to use a single instance per request app.CreatePerOwinContext(BlogIdentityDbContext.Create); app.CreatePerOwinContext<BlogUserManager>(BlogUserManager.Create); app.CreatePerOwinContext<BlogRoleManager>(BlogRoleManager.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("/api/account/login"), Provider = new BlogOAuthAuthorizationServerProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/account/externalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(120), AllowInsecureHttp = true }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); }
/// <summary> /// Se realiza la configuración de autorización /// </summary> /// <param name="app"></param> public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); googleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = "185157178718-8qc15td8nefjssrai2md8eiodr151m8u.apps.googleusercontent.com", ClientSecret = "tmnYb6S99BJPWVbv45Ha8Mf-", Provider = new GoogleAuthProvider() }; app.UseGoogleAuthentication(googleAuthOptions); }
public void ConfigureOAuth(IAppBuilder app) { OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); //Configure Google External Login googleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = "90666907944-o02ijc0nes4e6u26b7jmk7b6sr8dclr9.apps.googleusercontent.com", ClientSecret = "VwuUWkX4wCTn2UssEX4vfCP6", Provider = new GoogleAuthProvider() }; app.UseGoogleAuthentication(googleAuthOptions); //Configure Facebook External Login facebookAuthOptions = new FacebookAuthenticationOptions() { AppId = "146338829036652", AppSecret = "4c24328bfaa6d1801a98e72d91c3c600", Provider = new FacebookAuthProvider() }; app.UseFacebookAuthentication(facebookAuthOptions); }
// 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(SkyberryContext.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 { // access tokens Provider = new ApplicationOAuthProvider(PublicClientId), // using short lived access tokens coupled with long lived refresh tokens AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60), AllowInsecureHttp = true, // refresh tokens RefreshTokenProvider = new RefreshTokenProvider(), TokenEndpointPath = new PathString("/token"), }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); }
public static void ConfigureOAuthTokenGeneration(IAppBuilder app) { // configure database context and user manager to use a single instance per request app.CreatePerOwinContext(ngk.DataLayer.EFDbContext.AuthorizationContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); var token = new CustomJwtFormat("ngKBaseAngular"); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { // production should not allow insecure http AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20), Provider = new Providers.CustomOAuthProvider(), RefreshTokenProvider = new Providers.RefreshTokenProvider(), AccessTokenFormat = token }; // OAuth 2.0 Bearer Access Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(() => (ApplicationUserManager)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ApplicationUserManager))); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentityCallback: (manager, user) => GenerateUserIdentityAsync(manager, user), getUserIdCallback: (user) => (user.GetUserId<int>())) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; app.UseOAuthBearerTokens(OAuthOptions); }
public void ConfigureAuth(IAppBuilder app) { var config = new HttpConfiguration(); // TODO: figure out how to get client certificates // config.MessageHandlers.Add(new CertificateHandler()); config.MessageHandlers.Add(new ValidateRequestHandler()); OAuthBearerOptions = new OAuthAuthorizationServerOptions(); app.UseOAuthAuthorizationServer(OAuthBearerOptions); OAuthBearerAuthenticationOptions = new OAuthBearerAuthenticationOptions(); app.UseOAuthBearerAuthentication(OAuthBearerAuthenticationOptions); bool loadAssemblies = false; if (bool.TryParse(ConfigurationManager.AppSettings["LoadAssemblyForTest"], out loadAssemblies)) { config.Services.Replace(typeof(IAssembliesResolver), new AssemblyResolver()); } config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter("Bearer")); app.UseWebApi(config); }
// What is OAuth???? //OAuth is an open standard for authorization. OAuth provides client applications //a 'secure delegated access' to server resources on behalf of a resource owner. //It specifies a process for resource owners to authorize third-party access to their //server resources without sharing their credentials. public void ConfigureOAuth(IAppBuilder app) { //Here we’ve created new instance from class “OAuthAuthorizationServerOptions” //and set its option as the below: //1. //The path for generating tokens will be as :”http://localhost:port/token”. //We’ll see how we will issue HTTP POST request to generate token in the next steps. //2. //We’ve specified the expiry for token to be 24 hours, so if the user tried //to use the same token for authentication after 24 hours from the issue time, //his request will be rejected and HTTP status code 401 is returned. //3. //We’ve specified the implementation on how to validate the credentials for //users asking for tokens in custom class named “SimpleAuthorizationServerProvider”. OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
// 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( // new TwitterAuthenticationOptions // { // ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"], // ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"], // BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[] // { // "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 // "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 // "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 // "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 // "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5 // "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA // "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA // }) // } // ); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
public void ConfigureOAuth(IAppBuilder app) { // Configure authentication // The object below represents options for authentication // The default options are good for now so we're not going to change anything var authenticationOptions = new OAuthBearerAuthenticationOptions(); // Tell the app to use OAuthBearerAuthentication, passing in the authenticationOptions that we just instantiated app.UseOAuthBearerAuthentication(authenticationOptions); // Configure authorization // We do want to customize is how authorization works in our system // Same pattern as above, we're making options and then pass those options to the application var authorizationOptions = new OAuthAuthorizationServerOptions { // We are going to configure 4 properties here to customize authorization // We don't have https set up (secure set up) // So just for testing purposes, we're going to allow insecure http AllowInsecureHttp = true, // Because we're not writing a controller that accepts information (that's taken care of by ASP.Net.Identity) // We need to tell ASP.Net.Identity what route is; where is my user going to post to grab a token // We're telling it the endpoint path is a new path string and you have to hit /api/token to grab a token TokenEndpointPath = new PathString("/api/token"), // The token is only good for 1 day AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), // ASP.Net.Identity now wants to know where's the class that you wrote to intercept the events I'm going to throw at you Provider = new PropertyManagerAuthorizationServerProvider() }; app.UseOAuthAuthorizationServer(authorizationOptions); }
/// <summary> /// Static constructor to initialize values on application runtime /// </summary> static Startup() { // The "service" (our application) certifying a user's authentication status PublicClientId = "self"; // Sets the UserManagerFactory to an anonymous function that returns a new // instance of UserManager<IdentityUser>. This factory can be called from // anywhere in the application as Startup.UserManagerFactory() to get a properly // configured instance of the UserManager UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new AuthenticationDbContext())); // http://stackoverflow.com/questions/19571131/how-to-implement-a-unit-of-work-containing-the-new-identityuser //http://stackoverflow.com/questions/20790990/why-does-the-asp-net-spa-template-instantiate-usermanager-once-for-all-requests // Options which the authentication system will use OAuthOptions = new OAuthAuthorizationServerOptions { // Point at which the Bearer token middleware will be mounted TokenEndpointPath = new PathString("/token"), // An implementation of the OAuthAuthorizationServerProvider which the middleware // will use for determining whether a user should be authenticated or not Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), // How long a bearer token should be valid for AccessTokenExpireTimeSpan = TimeSpan.FromHours(24), // Allows authentication over HTTP instead of forcing HTTPS AllowInsecureHttp = true, AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), }; }
private void ConfigureOAuth(IAppBuilder app) { var oAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/api/account/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new AuthorizationServerProvider() }; app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); app.UseOAuthAuthorizationServer(oAuthServerOptions); app.Use(async (context, next) => { var request = context.Request; var response = context.Response; if (request.Path.StartsWithSegments(oAuthServerOptions.TokenEndpointPath)) { var origin = request.Headers.Get("Origin"); if (!string.IsNullOrEmpty(origin)) { response.Headers.Set("Access-Control-Allow-Origin", origin); } if (request.Method == "OPTIONS") { response.StatusCode = 200; response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST"); response.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type"); return; } } await next(); }); }
public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(MessagesDbContext.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. Do it only once! if (OAuthOptions == null) { PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString(TokenEndpointPath), Provider = new ApplicationOAuthProvider(PublicClientId), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; } // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); }
// 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(DBContext.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"), //If the AccessTokenExpireTimeSpan is changed, also change the ExpiresUtc in the RefreshTokenProvider.cs. AccessTokenExpireTimeSpan = TimeSpan.FromHours(2), AllowInsecureHttp = true, RefreshTokenProvider = new RefreshTokenProvider() }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); }
// 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 }; // Token Generation app.UseOAuthAuthorizationServer(OAuthOptions); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); app.UseOAuthBearerAuthentication(OAuthBearerOptions); facebookAuthOptions = new FacebookAuthenticationOptions { AppId = "1543886725935090", AppSecret = "63ab7a49e991177caf72e3ec8f2247cc", Provider = new FacebookAuthProvider() }; app.UseFacebookAuthentication(facebookAuthOptions); }
public void Configuration(IAppBuilder app) { SecurityConfig.Config(); var oauthServerConfig = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions { AllowInsecureHttp = false, AccessTokenExpireTimeSpan = TimeSpan.FromHours(2), Provider = new AuthorizationServerProvider(), TokenEndpointPath = new PathString("/token") }; app.UseOAuthAuthorizationServer(oauthServerConfig); var oauthConfig = new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active //AuthenticationType = "Bearer" }; app.UseOAuthBearerAuthentication(oauthConfig); var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(1); GlobalHost.Configuration.LongPollDelay = TimeSpan.FromMilliseconds(5000); app.MapSignalR(); }
public AccountController(IdentityManager identityManager, OAuthAuthorizationServerOptions oAuthOptions, CookieAuthenticationOptions cookieOptions) { IdentityManager = identityManager; OAuthOptions = oAuthOptions; CookieOptions = cookieOptions; }
public void Configuration(IAppBuilder app) { ConfigureMembershipReboot(app); var oauthServerConfig = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions { AllowInsecureHttp = true, Provider = new MyProvider(), TokenEndpointPath = new PathString("/token") }; app.UseOAuthAuthorizationServer(oauthServerConfig); var oauthConfig = new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AuthenticationType = "Bearer" }; app.UseOAuthBearerAuthentication(oauthConfig); var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); app.UseWebApi(config); }
// 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(ErisSystemContext.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); app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // 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); }
public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // Note: Remove the following line before you deploy to production: AllowInsecureHttp = true }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); app.UseWebApi(config); }
public void ConfigureOAuth(IAppBuilder app, HttpConfiguration config) { UserManagerFactory = () => { try { var userRepository = config.DependencyResolver.GetService(typeof(IUserRepository)); var userManager = new ApplicationUserManager(userRepository as IUserRepository); return userManager; } catch (Exception) { return null; } }; app.CreatePerOwinContext(UserManagerFactory); var oAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationProvider() }; app.UseOAuthAuthorizationServer(oAuthServerOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
//private static UserManager<Identity> CreateManager(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context) //{ // var userStore = new UserStore<IdentityUser>(context.Get<System.Data.Linq.DataContext>()); // var owinManager = new UserManager<IdentityUser>(userStore); // return owinManager; //} public void ConfigureOAuth(Owin.IAppBuilder app) { Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions OAuthOptions = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromHours(8), Provider = new ApplicationOAuthProvider() }; app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // 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: ""); #region ServerOAuth app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions () { AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, AuthenticationType = "Emad", Realm = "EHM" //anything }); var options = new Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerOptions(); options.TokenEndpointPath = new PathString("/account/token"); options.AuthorizeEndpointPath = new PathString("/account/auth"); options.AllowInsecureHttp = true; //Don't do that!! always be on secure scheme, this is set to "true" for demo purposes var provider = new OAuthAuthorizationServerProvider(); provider.OnValidateClientRedirectUri = (context) => { return(Task.Run(() => { //Caution: this is not to validate that the uri is valid syntax wise, this is to validate it business wise. If this uri is not //valid syntax wise this entry will not be hit in the first place, and your authentication process will not work! context.Validated(); })); }; provider.OnValidateAuthorizeRequest = (context) => { return(Task.Run(() => { //Authorization validation here //Somewhere in the request you should create the identity and sign in with it, I put it here, it could be a page on your app? context.OwinContext.Authentication.SignIn(new System.Security.Claims.ClaimsIdentity("Bearer")); context.Validated(); })); }; provider.OnAuthorizeEndpoint = (context) => { return(Task.Run(() => { //This is the last chance to alter the request, you can either end it here using RequestCompleted and start resonding, //or you can let it go through to the subsequent middleware, //except that you have to make sure the response returns a 200, otherwise the whole thing will not work context.RequestCompleted(); var str = context.Options.AccessTokenFormat; })); }; provider.OnValidateClientAuthentication = (context) => { return(Task.Run(() => { //Client validation here context.Validated(); })); }; options.Provider = provider; AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider(); authTokenProvider.OnCreate = (context) => { //create a dummy token context.SetToken("MyTokenblablabla"); }; //This is called when a client is requesting with Authorization header and passing the token, like this "Authorization: Bearer jdksjkld" authTokenProvider.OnReceive = (context) => { //create dummy identity regardless of the validty of the token :) var claimsIdentity = new System.Security.Claims.ClaimsIdentity("Bearer"); claimsIdentity.AddClaim(new Claim("something", "Ahmad")); //This claim type "something" is used for protection from anti-forgery... //Check the Global.asax for "AntiForgeryConfig.UniqueClaimTypeIdentifier = "something";" //you can avoid setting this, but you have to use the default claims type. check http://bartwullems.blogspot.com.au/2013/09/aspnet-mvc-4-error-when-using-anti.html context.SetTicket(new Microsoft.Owin.Security.AuthenticationTicket(claimsIdentity, new Microsoft.Owin.Security.AuthenticationProperties { ExpiresUtc = new System.DateTimeOffset(2015, 3, 1, 1, 1, 1, new System.TimeSpan()), } )); }; options.AuthorizationCodeProvider = authTokenProvider; options.RefreshTokenProvider = authTokenProvider; options.AccessTokenProvider = authTokenProvider; app.UseOAuthBearerTokens(options); #endregion //app.UseGoogleAuthentication(); }
static Startup() { PublicClientId = "self"; UserManagerFactory = () => { var context = new IdentityDbContext(); System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer()); var userStore = new UserStore<IdentityUser>(context); userStore.DisposeContext = true; return new UserManager<IdentityUser>(userStore); }; RoleManagerFactory = () => { var context = new IdentityDbContext(); System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer()); var roleStore = new RoleStore<IdentityRole>(context); return new RoleManager<IdentityRole>(roleStore); }; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true }; }