Beispiel #1
0
        //[HttpGet]
        //[Route("CountryList")]
        //public IHttpActionResult CountryList()
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listCountries = generalBusiness.GetAllCountries();

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "country list updated successfully";
        //        responseData.data = listCountries;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}
        //[HttpGet]
        //[Route("StateList/{countryId}")]
        //public IHttpActionResult StateList(Guid countryId)
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listStates = generalBusiness.GetStatesByCountry(countryId);

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "states list updated successfully";
        //        responseData.data = listStates;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}
        //[HttpGet]
        //[Route("CityList/{stateId}")]
        //public IHttpActionResult CityList(Guid stateId)
        //{
        //    try
        //    {
        //        GeneralBusiness generalBusiness = new GeneralBusiness(false);
        //        var listCities = generalBusiness.GetCitiesByState(stateId);

        //        responseData.success = true;
        //        responseData.code = 200;
        //        responseData.message = "cities list updated successfully";
        //        responseData.data = listCities;
        //        return Ok(responseData);
        //    }
        //    catch (Exception ex)
        //    {
        //        responseData.message = "server error";
        //        return Ok(responseData);
        //    }
        //}

        /// <summary>
        /// Create access token and refresh token for user login with facebook or google
        /// </summary>
        /// <param name="objUser">User Model Object</param>
        /// <returns>Return Json object with access_token and refresh_token</returns>
        private UserTokenViewModel GenerateAccessTokenForUser(UsersModel userVM)
        {
            var tokenExpirationTimeSpan = TimeSpan.FromDays(1);
            // var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
            //identity.AddClaim(new Claim(ClaimTypes.Role, userVM.UserType));
            //identity.AddClaim(new Claim(ClaimTypes.Email, userVM.EmailID));
            //identity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.UserID)));

            ClaimsIdentity oAuthIdentity =
                new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);

            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, Convert.ToString(userVM.RefType)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Sid, Convert.ToString(userVM.RefID)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, Convert.ToString(userVM.UserID)));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Email, userVM.Email));

            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
            var currentUtc = new Microsoft.Owin.Infrastructure.SystemClock().UtcNow;

            ticket.Properties.IssuedUtc  = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(tokenExpirationTimeSpan);
            var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
            AuthenticationTokenCreateContext rtokenContext = new AuthenticationTokenCreateContext(HttpContext.Current.GetOwinContext(), Startup.OAuthOptions.AccessTokenFormat, ticket);

            AuthenticationTokenProvider rtokenProvider = new AuthenticationTokenProvider();
            var refresh_token            = rtokenProvider.CreateRefreshToken(rtokenContext);
            UserTokenViewModel userToken = new UserTokenViewModel();

            userToken.access_token  = accessToken;
            userToken.expires_in    = tokenExpirationTimeSpan.TotalSeconds.ToString();
            userToken.refresh_token = refresh_token;
            return(userToken);
        }
Beispiel #2
0
        public SideKickOAuthImplementation()
        {
            AuthorizeEndpointPath       = new PathString("/oauth/authorize");
            TokenEndpointPath           = new PathString("/oauth/token");
            ApplicationCanDisplayErrors = true;
            AllowInsecureHttp           = true;
            Provider = new SidekickOAuthProvider();


            AuthorizationCodeProvider = new AuthenticationTokenProvider
            {
                OnCreate  = CreateAuthenticationCode,
                OnReceive = ReceiveAuthenticationCode,
            };

            RefreshTokenProvider = new AuthenticationTokenProvider
            {
                OnCreate  = CreateRefreshToken,
                OnReceive = ReceiveRefreshToken,
            };

            // AccessTokenExpireTimeSpan = TimeSpan.FromHours(1); //modify during production..you might wanna read from db

            AccessTokenFormat = new SidekickJwtFormat(this);
        }
    public void ConfigureOAuth(IAppBuilder app)
    {
        AuthenticationTokenProvider authTokenProvider = new AuthenticationTokenProvider();

        authTokenProvider.OnCreate = (context) =>
        {
            context.SetToken(TokenService.GenerateToken());
        };
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp         = true,
            Provider                  = new SimpleAuthorizationServerProvider(),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(TokenService.expireTime),
            AccessTokenProvider       = authTokenProvider,
            AuthorizationCodeProvider = authTokenProvider
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
 public DeviceSocket(AuthenticationTokenProvider tokenProvider, ILoggerFactory loggerFactory)
 {
     _tokenProvider = tokenProvider;
     _loggerFactory = loggerFactory;
 }
Beispiel #5
0
        // 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();
        }
Beispiel #6
0
 public UserContext(AuthenticationTokenProvider provider)
 {
     _provider = provider;
 }
Beispiel #7
0
        /// <summary>
        /// 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください
        ///
        /// Code! MVC 5 App with Facebook, Twitter, LinkedIn
        /// and Google OAuth2 Sign-on (C#) | The ASP.NET Site
        /// http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
        /// </summary>
        /// <param name="app">app</param>
        public static void Configure(IAppBuilder app)
        {
            // 1 要求につき 1 インスタンスのみを使用するように
            // DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。

            // Add to OwinContext.

            #region AuthenticationType

            // AuthenticationType:
            //   ClaimsIdentity生成時や、AuthenticationTicket取得時に指定する。

            // --------------------------------------------------
            // OAuthDefaultsクラス (Microsoft.Owin.Security)
            // https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.aspx
            // --------------------------------------------------
            // - OAuthDefaults.AuthenticationType フィールド (Microsoft.Owin.Security.OAuth)
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.authenticationtype.aspx
            //   OAuthBearerAuthenticationOptions と OAuthAuthorizationServerOptions の AuthenticationType プロパティの既定値。
            //   - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security)
            //     https://msdn.microsoft.com/ja-jp/library/dn300391.aspx
            //   - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security)
            //     https://msdn.microsoft.com/ja-jp/library/dn300391.aspx
            // --------------------------------------------------

            // --------------------------------------------------
            // DefaultAuthenticationTypes クラス (Microsoft.AspNet.Identity)
            // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.aspx
            // --------------------------------------------------
            // - ApplicationCookie
            //   Forms認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.applicationcookie.aspx
            // - TwoFactorRememberBrowserCookie
            //   Browser認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorrememberbrowsercookie.aspx
            // - TwoFactorCookie
            //   TwoFactor認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorcookie.aspx
            // - ExternalCookie
            //   外部ログイン Cookie認証チケット
            //   /userinfoやid_tokenの情報をCookieに格納してある。
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalcookie.aspx
            // - ExternalBearer
            //   Bearer TokenのUnprotectする際、ClaimsIdentityに指定。
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalbearer.aspx
            // --------------------------------------------------

            #endregion

            #region EntityFramework
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            #endregion

            #region EntityFramework以外

            #region UserStore, ApplicationUserManager, RoleManager, SignInManagerのOwinContextを生成

            // UserStoreのOwinContextを生成
            app.CreatePerOwinContext <UserStore>(() => new UserStore());

            // ApplicationUserManagerのOwinContextを生成
            // 以下を設定する
            // - ユーザ名検証
            // - パスワード検証
            // - ユーザ ロックアウト
            // - 2FAプロバイダ
            // - 暗号化プロバイダ
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // ApplicationRoleManagerのOwinContextを生成
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // ApplicationSignInManagerのOwinContextを生成
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            #endregion

            #region UseCookieAuthenticationのOwinContextを生成

            // 次を設定
            // - AuthenticationType
            // - LoginPath
            // - Provider
            // - SecurityStamp

            // 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 configure the sign in cookie.

            // アプリケーションがユーザのサイン・イン情報をCookie認証チケットに一時的に保存するようにします。
            // また、サードパーティのプロバイダでログインするユーザ情報もCookie認証チケットを使用してできるようにします。
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,  // 認証タイプを設定する。
                LoginPath          = new PathString("/Account/Login"),              // ログイン画面のパスを設定する。

                Provider = new CookieAuthenticationProvider                         // 認証プロバイダを設定する(ICookieAuthenticationProvider の既定の実装)。
                {
                    #region SecurityStamp

                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.

                    // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。
                    // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。

                    // --------------------------------------------------
                    // SecurityStampValidator.OnValidateIdentity
                    // --------------------------------------------------
                    // パスワードの変更や、外部ログインを追加した際に、全てのログインセッションを
                    // 無効化できるようCookie認証チケットに、ログインに紐付くセキュリティスタンプを埋め込んでいる。
                    // http://kendik.hatenablog.com/entry/2014/08/17/212645
                    // --------------------------------------------------
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        // SecurityStampValidatorによる検証の間隔
                        validateInterval: ASPNETIdentityConfig.SecurityStampValidateIntervalFromSeconds,
                        // ClaimsIdentityを返すdelegate
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

                                         #endregion
                },

                // Cookie認証チケットの有効期限
                ExpireTimeSpan = ASPNETIdentityConfig.AuthCookieExpiresFromHours,
                // Cookie認証チケットの有効期限を半分過ぎた祭の要求で再発行(Sliding)される。
                SlidingExpiration = ASPNETIdentityConfig.AuthCookieSlidingExpiration,
            });

            #endregion

            #region UseExternalSignInCookieのOwinContextを生成

            // 外部アイデンティティのためOWINミドルウェアベースの
            // Cookie認証を使用するようにアプリケーションを設定します。
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            #endregion

            #region UseTwoFactor(2FA)のOwinContextを生成

            #region SignInCookie(2FAのCookie認証チケット)

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            // 2FAプロセスにおいて第 2 認証要素を検証しているユーザの情報を一時的に格納するようにします。
            app.UseTwoFactorSignInCookie(
                authenticationType: DefaultAuthenticationTypes.TwoFactorCookie,
                expires: ASPNETIdentityConfig.TwoFactorCookieExpiresFromHours);

            #endregion

            #region RememberBrowserCookie(2FAのブラウザ記憶)

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.

            // 電話や電子メールなど2FAのログイン検証係数を記憶するようにアプリケーションを設定します。
            // このオプションをチェックすると、ログイン時プロセスの第二検証ステップでログインデバイス上に記憶されます。
            // これは、ログイン時の「このアカウントを記憶する」オプションに似ています。

            app.UseTwoFactorRememberBrowserCookie(
                DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            #endregion

            #endregion

            #region Use(External)AuthenticationのOwinContextを生成

            // c# - Get E-mail of User Authenticated with Microsoft Account in ASP.NET Identity - Stack Overflow
            // http://stackoverflow.com/questions/22229593/get-e-mail-of-user-authenticated-with-microsoft-account-in-asp-net-identity

            #region MicrosoftAccountAuthentication

            if (ASPNETIdentityConfig.MicrosoftAccountAuthentication)
            {
                MicrosoftAccountAuthenticationOptions options = new MicrosoftAccountAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ClientId     = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientId,
                    ClientSecret = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientSecret
                };
                // スコープを追加する。
                options.Scope.Add("wl.basic");
                options.Scope.Add("wl.emails");

                // MicrosoftAccountAuthenticationの有効化
                app.UseMicrosoftAccountAuthentication(options);
            }

            #endregion

            #region GoogleAuthentication

            if (ASPNETIdentityConfig.GoogleAuthentication)
            {
                GoogleOAuth2AuthenticationOptions options = new GoogleOAuth2AuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ClientId     = ASPNETIdentityConfig.GoogleAuthenticationClientId,
                    ClientSecret = ASPNETIdentityConfig.GoogleAuthenticationClientSecret
                };
                // スコープを追加する。
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");

                // GoogleAuthenticationの有効化
                app.UseGoogleAuthentication(options);
            }

            #endregion

            #region FacebookAuthentication

            if (ASPNETIdentityConfig.FacebookAuthentication)
            {
                FacebookAuthenticationOptions options = new FacebookAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    AppId     = ASPNETIdentityConfig.FacebookAuthenticationClientId,
                    AppSecret = ASPNETIdentityConfig.FacebookAuthenticationClientSecret,
                    Provider  = new FacebookAuthenticationProvider
                    {
                        OnAuthenticated = context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                            return(Task.FromResult(true));
                        }
                    }
                };
                // スコープを追加する。
                options.Scope.Add("email");

                // FacebookAuthenticationの有効化
                app.UseFacebookAuthentication(options);
            }

            #endregion

            #region TwitterAuthentication

            if (ASPNETIdentityConfig.TwitterAuthentication)
            {
                TwitterAuthenticationOptions options = new TwitterAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ConsumerKey    = ASPNETIdentityConfig.TwitterAuthenticationClientId,
                    ConsumerSecret = ASPNETIdentityConfig.TwitterAuthenticationClientSecret,

                    Provider = new TwitterAuthenticationProvider
                    {
                        OnAuthenticated = (context) =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken));
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret));
                            return(Task.FromResult(0));
                        }
                    },

                    BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                        new string[] {
                        "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
                        "5168FF90AF0207753CCCD9656462A212B859723B",      // DigiCert SHA2 High Assurance Server C‎A
                        "B13EC36903F8BF4701D498261A0802EF63642BC3"
                    }                                                    // DigiCert High Assurance EV Root CA
                        ),
                };

                // スコープを追加する。
                // ・・・

                // TwitterAuthenticationの有効化
                app.UseTwitterAuthentication(options);
            }

            #endregion

            #endregion

            #region OAuth Endpointの追加

            // asp.net identity - UseOAuthBearerTokens vs UseOAuthBearerAuthentication - Stack Overflow
            // http://stackoverflow.com/questions/28048355/useoauthbearertokens-vs-useoauthbearerauthentication
            //   Pseudocode from source using reflector:
            //   UseOAuthAuthorizationServer();  // authorization server middleware.
            //   UseOAuthBearerAuthentication(); // application bearer token middleware.
            //   UseOAuthBearerAuthentication(); // external bearer token middleware.
            //   UseOAuthBearerTokens();         // extension method creates both the token server
            //                                   //   and the middleware to validate tokens for requests in the same application.

            // c# - ASP.Net identity: Difference between UseOAuthBearerTokens and UseCookieAuthentication? - Stack Overflow
            // http://stackoverflow.com/questions/22121330/asp-net-identity-difference-between-useoauthbearertokens-and-usecookieauthentic

            if (ASPNETIdentityConfig.EquipOAuthServer)
            {
                // OAuth Bearer Tokenを使用可能に設定する。
                // UseOAuthAuthorizationServerとUseOAuthBearerTokensの違いが不明だが、
                // UseOAuthAuthorizationServerだとOAuthBearerTokenEndpointPathが動かない。

                #region UseOAuthAuthorizationServer

                /*
                 * // --------------------------------------------------
                 * // OAuthAuthorizationServerを設定する。
                 * // --------------------------------------------------
                 * // OAuthAuthorizationServerExtensions.UseOAuthAuthorizationServer メソッド (Owin)
                 * // https://msdn.microsoft.com/ja-jp/library/dn270711.aspx
                 * // --------------------------------------------------
                 * // 参考:https://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
                 * app.UseOAuthAuthorizationServer(
                 *  new OAuthAuthorizationServerOptions
                 *  {
                 *      Provider = new ApplicationOAuthAuthorizationServerProvider(),
                 *      AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints,
                 *      ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors,
                 *      AuthorizeEndpointPath = ASPNETIdentityConfig.OAuthAuthorizeEndpointPath,
                 *      AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes,
                 *
                 *      // Authorization code provider which creates and receives the authorization code.
                 *      AuthorizationCodeProvider = new AuthenticationTokenProvider
                 *      {
                 *          OnCreate = CreateAuthenticationCode,
                 *          OnReceive = ReceiveAuthenticationCode,
                 *      },
                 *
                 *      // Refresh token provider which creates and receives refresh token.
                 *      RefreshTokenProvider = new AuthenticationTokenProvider
                 *      {
                 *          OnCreate = CreateRefreshToken,
                 *          OnReceive = ReceiveRefreshToken,
                 *      }
                 *  });
                 */

                #endregion

                #region UseOAuthBearerAuthentication

                // --------------------------------------------------
                // Resource Server単品を実装する際のメソッドであるもよう。
                // --------------------------------------------------

                //app.UseOAuthBearerAuthentication(
                //    new OAuthBearerAuthenticationOptions
                //    {
                //    });

                #endregion

                #region UseOAuthBearerTokens

                // --------------------------------------------------
                // OAuth Bearer Tokenを使用可能に設定する。
                // --------------------------------------------------
                // AppBuilderExtensions.UseOAuthBearerTokens Method (IAppBuilder, OAuthAuthorizationServerOptions) (Owin)
                // https://msdn.microsoft.com/ja-jp/library/owin.appbuilderextensions.useoauthbearertokens.aspx
                // --------------------------------------------------
                AuthenticationTokenProvider atp = new AuthenticationTokenProvider();

                // 以下のOAuth 2.0のフロー定義をサポートする。
                // ・Implicitグラント種別
                // ・Resource Owner Password Credentialsグラント種別
                // ・Client Credentialsグラント種別
                OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions =
                    new OAuthAuthorizationServerOptions
                {
                    #region 全てのグラント種別の共通設定

                    // ・Provider
                    //   OAuthAuthorizationServerProviderの派生クラスである、
                    //   ApplicationOAuthBearerTokenProvider(UseOAuthBearerTokens用)を設定する。
                    //   以下の4つのメソッドをオーバーライドする。
                    //   ・OnValidateClientRedirectUriプロパティ設定 or ValidateClientRedirectUriのオーバーライド
                    //   ・OnValidateClientAuthenticationプロパティ設定 or ValidateClientAuthenticationのオーバーライド
                    //   ・OnGrantResourceOwnerCredentialsプロパティ設定 or GrantResourceOwnerCredentialsのオーバーライド
                    //   ・OnGrantClientCredentialsプロパティ設定 or GrantClientCredentialsのオーバーライド
                    Provider = new ApplicationOAuthBearerTokenProvider(),

                    //AccessTokenFormat = new AccessTokenFormatJwt(),

                    // ・AccessTokenExpireTimeSpan(OAuth Access Token の 有効期限
                    AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes,     // System.TimeSpan.FromSeconds(10), // Debug時

                    // ・AllowInsecureHttp
                    //   認証して、Token要求が http URI アドレスに届くことを許可し、
                    //   受信する redirect_uri 承認要求パラメータに http URI アドレスを設定する場合は true。
                    AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints,

                    #endregion

                    #region  Implicitグラント種別を除く全てのグラント種別の共通設定

                    // ・OAuth Bearer Token の Token Endpoint
                    TokenEndpointPath = new PathString(ASPNETIdentityConfig.OAuthBearerTokenEndpoint),

                    #endregion

                    #region Authorization Code, Implicitグラント種別の共通設定

                    // ・AuthorizeEndpointPath
                    //   OAuth の Authorize Endpoint
                    AuthorizeEndpointPath = new PathString(ASPNETIdentityConfig.OAuthAuthorizeEndpoint),

                    // ・ApplicationCanDisplayErrors
                    //   AuthorizeEndpointPath上でエラー メッセージを表示できるようにする。
                    ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors,

                    #endregion

                    #region Authorization Codeグラント種別

                    #region AuthorizationCodeProvider
                    //   1 回だけ使用する認証コードを生成して、クライアント アプリケーションに返す。
                    //   OnCreate または OnCreateAsync イベントによって生成されたトークンは、
                    //   OnReceive または OnReceiveAsync イベントへの呼び出しに対して、一度だけ有効となる。
                    //   Authorization code provider which creates and receives authorization code
                    AuthorizationCodeProvider = new AuthenticationTokenProvider
                    {
                        OnCreate  = AuthorizationCodeProvider.GetInstance().Create,
                        OnReceive = AuthorizationCodeProvider.GetInstance().Receive,
                        //OnCreateAsync = AuthorizationCodeProvider.GetInstance().CreateAsync,
                        //OnReceiveAsync = AuthorizationCodeProvider.GetInstance().ReceiveAsync,
                    },
                    #endregion

                    #region  RefreshTokenProvider
                    //   必要に応じて、新しいAccessTokenの生成に使うことができるRefresh Tokenを生成する。
                    //   RefreshTokenProviderが提供されない場合、OAuthBearerTokenEndpointPathからRefresh Tokenが返されない。
                    //   Refresh token provider which creates and receives referesh token
                    RefreshTokenProvider = new AuthenticationTokenProvider
                    {
                        OnCreate  = RefreshTokenProvider.GetInstance().Create,
                        OnReceive = RefreshTokenProvider.GetInstance().Receive,
                        //OnCreateAsync = RefreshTokenProvider.GetInstance().CreateAsync,
                        //OnReceiveAsync = RefreshTokenProvider.GetInstance().ReceiveAsync,
                    },
                    #endregion

                    #endregion
                };

                #region Options可変部分

                // AccessTokenFormat(OAuth Access Token の Format をJWTフォーマットに変更する。
                oAuthAuthorizationServerOptions.AccessTokenFormat = new AccessTokenFormatJwt();

                #endregion

                // UseOAuthBearerTokensにOAuthAuthorizationServerOptionsを設定
                app.UseOAuthBearerTokens(oAuthAuthorizationServerOptions);

                #endregion
            }

            #endregion

            #endregion
        }