示例#1
0
 public override Task <TokenResponseDTO> Refresh(TokenRefreshRequestDTO request, ServerCallContext context)
 {
     return(Task.Run(() =>
     {
         TokenResponseDTO response = new TokenResponseDTO();
         RefreshTokenProvider refresh = new RefreshTokenProvider(request.Appid, request.RefreshToken);
         if (!refresh.Refresh())
         {
             response.RetMsg = refresh.PromptInfo.CustomMessage;
             response.RetCode = refresh.PromptInfo.ResultType <= 0 ? "0500" : ((int)refresh.PromptInfo.ResultType).ToString().PadLeft(4, '0');
             return response;
         }
         response.RetCode = "0000";
         response.RetMsg = "ok";
         response.Data = new TokenResponseDTO.Types.Result
         {
             RefreshToken = refresh.OAuthUser.Refresh_Token,
             Expires = refresh.OAuthUser.Expire_In,
             Openid = refresh.OAuthUser.Open_Id,
             RefreshExpires = refresh.OAuthUser.Refresh_Expire_In,
             Token = refresh.OAuthUser.Token
         };
         return response;
     }));
 }
示例#2
0
        // https://stackoverflow.com/questions/25739710/how-to-create-refresh-token-with-external-login-provider
        private async Task <AuthenticationProperties> AddRefreshToken(ClaimsIdentity oAuthIdentity, AuthenticationProperties properties)
        {
            try
            {
                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

                AuthenticationTokenCreateContext context = new AuthenticationTokenCreateContext(
                    Request.GetOwinContext(),
                    Startup.OAuthOptions.AccessTokenFormat,
                    ticket);

                await Startup.OAuthOptions.RefreshTokenProvider.CreateAsync(context);

                DateTimeOffset?refreshExpires = RefreshTokenProvider.GetExpiryDate(context.Token, Request.GetOwinContext());
                properties.Dictionary.Add("refresh_token", context.Token);
                properties.Dictionary.Add("refresh_token_expires", (refreshExpires == null) ? DateTime.UtcNow.Ticks.ToString() : ((DateTimeOffset)refreshExpires).UtcTicks.ToString());

                return(properties);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }
        public async void RefreshTokenProvider_GetRefreshToken_ReturnsTokenIsNotRevoked()
        {
            var expirationData       = new DateTime(2018, 04, 14);
            var refreshTokenProvider = new RefreshTokenProvider();

            var token = await refreshTokenProvider.GetRefreshToken(expirationData);

            Assert.False(token.Revoked);
        }
        public async void RefreshTokenProvider_GetRefreshToken_ReturnsTokenWithExpirationDataSet()
        {
            var expirationData       = new DateTime(2018, 04, 14);
            var refreshTokenProvider = new RefreshTokenProvider();

            var token = await refreshTokenProvider.GetRefreshToken(expirationData);

            Assert.Equal(expirationData, token.ExpirationDate);
        }
        public async Task <IHttpActionResult> TokenRefreshSuccess(string oldToken)
        {
            var entities    = new ApplicationDbContext();
            var repo        = new ApplicationRepository(entities);
            var hashedToken = RefreshTokenProvider.GetHash(oldToken);
            await repo.RefreshTokens.DeleteAndSaveAsync(hashedToken);

            return(Ok());
        }
        public async void RefreshTokenProvider_GetRefreshToken_ReturnsTokenWithTokenValueSet()
        {
            var expirationData       = new DateTime(2018, 04, 14);
            var refreshTokenProvider = new RefreshTokenProvider();

            var token = await refreshTokenProvider.GetRefreshToken(expirationData);

            Assert.NotNull(token);
            Assert.NotEmpty(token.TokenValue);
        }
示例#7
0
        /// <summary>
        /// 刷新授权Token
        /// </summary>
        /// <param name="appid">应用账号</param>
        /// <param name="refresh_token">刷新令牌</param>
        /// <param name="grant_type">授权类型=refresh_token</param>
        /// <returns></returns>
        public ActionResult RefreshToken(string appid, string refresh_token, string grant_type)
        {
            JsonResult           jsonRes = null;
            RefreshTokenProvider refresh = new RefreshTokenProvider(appid, refresh_token);

            if (!refresh.Refresh())
            {
                jsonRes = FailResult(refresh.PromptInfo.CustomMessage, (int)refresh.PromptInfo.ResultType);
                jsonRes.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                return(jsonRes);
            }
            jsonRes = SuccessResult(refresh.OAuthUser);
            jsonRes.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
            return(jsonRes);
        }
示例#8
0
        public ResponseResult <TokenResponseDTO> Refresh(TokenRefreshRequestDTO request)
        {
            RefreshTokenProvider refresh = new RefreshTokenProvider(request.Appid, request.RefreshToken);

            if (!refresh.Refresh())
            {
                return(Fail <TokenResponseDTO>(refresh.PromptInfo.CustomMessage));
            }

            TokenResponseDTO response = new TokenResponseDTO
            {
                RefreshToken   = refresh.OAuthUser.Refresh_Token,
                Expires        = refresh.OAuthUser.Expire_In,
                Openid         = refresh.OAuthUser.Open_Id,
                RefreshExpires = refresh.OAuthUser.Refresh_Expire_In,
                Token          = refresh.OAuthUser.Token
            };

            return(Success(response));
        }
示例#9
0
        //[Authorize]
        public Dictionary <string, string> IntrospectToken(FormDataCollection formData)
        {
            // 戻り値
            // ・正常
            Dictionary <string, string> ret = new Dictionary <string, string>();
            // ・異常
            Dictionary <string, string> err = new Dictionary <string, string>();

            // 変数
            string[] temp            = null;
            string   token           = formData[OAuth2AndOIDCConst.token];
            string   token_type_hint = formData[OAuth2AndOIDCConst.token_type_hint];

            // クライアント認証

            // クライアント識別子
            string authHeader = HttpContext.Current.Request.Headers[OAuth2AndOIDCConst.HttpHeader_Authorization];

            temp = authHeader.Split(' ');

            if (temp[0] == OAuth2AndOIDCConst.Basic)
            {
                temp = CustomEncode.ByteToString(
                    CustomEncode.FromBase64String(temp[1]), CustomEncode.us_ascii).Split(':');

                string clientId     = temp[0];
                string clientSecret = temp[1];

                if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                {
                    // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                    if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(clientId))
                    {
                        // 検証完了
                        AuthenticationTicket ticket = null;

                        if (token_type_hint == OAuth2AndOIDCConst.AccessToken)
                        {
                            // 検証
                            AccessTokenFormatJwt verifier = new AccessTokenFormatJwt();
                            ticket = verifier.Unprotect(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功
                                // メタデータの返却
                                ret.Add("active", "true");
                                ret.Add(OAuth2AndOIDCConst.token_type, token_type_hint);

                                string scopes = "";
                                foreach (Claim claim in ticket.Identity.Claims)
                                {
                                    if (claim.Type.StartsWith(OAuth2AndOIDCConst.Claim_Base))
                                    {
                                        if (claim.Type == OAuth2AndOIDCConst.Claim_Scopes)
                                        {
                                            scopes += claim.Value + " ";
                                        }
                                        else
                                        {
                                            ret.Add(claim.Type.Substring(
                                                        OAuth2AndOIDCConst.Claim_Base.Length), claim.Value);
                                        }
                                    }
                                }
                                ret.Add(OAuth2AndOIDCConst.Claim_Scopes.Substring(
                                            OAuth2AndOIDCConst.Claim_Base.Length), scopes.Trim());

                                return(ret); // 成功
                            }
                        }
                        else if (token_type_hint == OAuth2AndOIDCConst.RefreshToken)
                        {
                            // refresh_token参照
                            ticket = RefreshTokenProvider.ReferDirectly(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功
                                // メタデータの返却
                                ret.Add("active", "true");
                                ret.Add(OAuth2AndOIDCConst.token_type, token_type_hint);

                                string scopes = "";
                                foreach (Claim claim in ticket.Identity.Claims)
                                {
                                    if (claim.Type.StartsWith(OAuth2AndOIDCConst.Claim_Base))
                                    {
                                        if (claim.Type == OAuth2AndOIDCConst.Claim_Scopes)
                                        {
                                            scopes += claim.Value + " ";
                                        }
                                        else
                                        {
                                            ret.Add(claim.Type.Substring(
                                                        OAuth2AndOIDCConst.Claim_Base.Length), claim.Value);
                                        }
                                    }
                                }
                                ret.Add(OAuth2AndOIDCConst.Claim_Scopes.Substring(
                                            OAuth2AndOIDCConst.Claim_Base.Length), scopes.Trim());

                                return(ret); // 成功
                            }
                        }
                        else
                        {
                            // token_type_hint パラメタ・エラー
                            err.Add("error", "invalid_request");
                            err.Add("error_description", "invalid token_type_hint");
                        }
                    }
                    else
                    {
                        // クライアント認証エラー(Credential不正
                        err.Add("error", "invalid_client");
                        err.Add("error_description", "Invalid credential");
                    }
                }
                else
                {
                    // クライアント認証エラー(Credential不正
                    err.Add("error", "invalid_client");
                    err.Add("error_description", "Invalid credential");
                }
            }
            else
            {
                // クライアント認証エラー(ヘッダ不正
                err.Add("error", "invalid_request");
                err.Add("error_description", "Invalid authentication header");
            }

            return(err); // 失敗
        }
示例#10
0
        //[Authorize]
        public Dictionary <string, string> RevokeToken(FormDataCollection formData)
        {
            // 戻り値(エラー)
            Dictionary <string, string> err = new Dictionary <string, string>();

            // 変数
            string[] temp            = null;
            string   token           = formData[OAuth2AndOIDCConst.token];
            string   token_type_hint = formData[OAuth2AndOIDCConst.token_type_hint];

            // クライアント認証

            // クライアント識別子
            string authHeader = HttpContext.Current.Request.Headers[OAuth2AndOIDCConst.HttpHeader_Authorization];

            temp = authHeader.Split(' ');

            if (temp[0] == OAuth2AndOIDCConst.Basic)
            {
                temp = CustomEncode.ByteToString(
                    CustomEncode.FromBase64String(temp[1]), CustomEncode.us_ascii).Split(':');

                string clientId     = temp[0];
                string clientSecret = temp[1];

                if (!(string.IsNullOrEmpty(clientId) && string.IsNullOrEmpty(clientSecret)))
                {
                    // *.config or OAuth2Dataテーブルを参照してクライアント認証を行なう。
                    if (clientSecret == OAuth2Helper.GetInstance().GetClientSecret(clientId))
                    {
                        // 検証完了

                        if (token_type_hint == OAuth2AndOIDCConst.AccessToken)
                        {
                            // 検証
                            AccessTokenFormatJwt verifier = new AccessTokenFormatJwt();
                            AuthenticationTicket ticket   = verifier.Unprotect(token);

                            if (ticket == null)
                            {
                                // 検証失敗
                                // 検証エラー
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                            else
                            {
                                // 検証成功

                                // jtiの取り出し
                                Claim jti = ticket.Identity.Claims.Where(
                                    x => x.Type == OAuth2AndOIDCConst.Claim_JwtId).FirstOrDefault <Claim>();

                                // access_token取消
                                OAuth2RevocationProvider.GetInstance().Create(jti.Value);
                                return(null); // 成功
                            }
                        }
                        else if (token_type_hint == OAuth2AndOIDCConst.RefreshToken)
                        {
                            // refresh_token取消
                            if (RefreshTokenProvider.DeleteDirectly(token))
                            {
                                // 取り消し成功
                                return(null); // 成功
                            }
                            else
                            {
                                // 取り消し失敗
                                err.Add("error", "invalid_request");
                                err.Add("error_description", "invalid token");
                            }
                        }
                        else
                        {
                            // token_type_hint パラメタ・エラー
                            err.Add("error", "invalid_request");
                            err.Add("error_description", "invalid token_type_hint");
                        }
                    }
                    else
                    {
                        // クライアント認証エラー(Credential不正
                        err.Add("error", "invalid_client");
                        err.Add("error_description", "Invalid credential");
                    }
                }
                else
                {
                    // クライアント認証エラー(Credential不正
                    err.Add("error", "invalid_client");
                    err.Add("error_description", "Invalid credential");
                }
            }
            else
            {
                // クライアント認証エラー(ヘッダ不正
                err.Add("error", "invalid_request");
                err.Add("error_description", "Invalid authentication header");
            }

            return(err); // 失敗
        }
示例#11
0
        public static void Configure(IAppBuilder app, IUnityContainer container)
        {
            app.CreatePerOwinContext(() => container.Resolve <SecurityDbContext>());
            app.CreatePerOwinContext(() => container.Resolve <ApplicationUserManager>());

            var origins = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:CORS:AllowedOrigins");

            if (!string.IsNullOrEmpty(origins))
            {
                var corsPolicy = new CorsPolicy
                {
                    AllowAnyMethod = true,
                    AllowAnyHeader = true
                };

                var originsArray = origins.Split(';');
                if (originsArray.Contains("*"))
                {
                    corsPolicy.AllowAnyOrigin = true;
                }
                else
                {
                    foreach (var origin in originsArray)
                    {
                        corsPolicy.Origins.Add(origin);
                    }
                }

                var corsOptions = new CorsOptions
                {
                    PolicyProvider = new CorsPolicyProvider
                    {
                        PolicyResolver = context => Task.FromResult(corsPolicy)
                    }
                };

                app.UseCors(corsOptions);
            }


            var authenticationOptions = container.Resolve <AuthenticationOptions>();

            if (authenticationOptions.CookiesEnabled)
            {
                // 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
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationMode = authenticationOptions.AuthenticationMode,
                    AuthenticationType = authenticationOptions.AuthenticationType,
                    CookieDomain       = authenticationOptions.CookieDomain,
                    CookieHttpOnly     = authenticationOptions.CookieHttpOnly,
                    CookieName         = authenticationOptions.CookieName,
                    CookiePath         = authenticationOptions.CookiePath,
                    CookieSecure       = authenticationOptions.CookieSecure,
                    ExpireTimeSpan     = authenticationOptions.ExpireTimeSpan,
                    LoginPath          = authenticationOptions.LoginPath,
                    LogoutPath         = authenticationOptions.LogoutPath,
                    ReturnUrlParameter = authenticationOptions.ReturnUrlParameter,
                    SlidingExpiration  = authenticationOptions.SlidingExpiration,
                    Provider           = new CookieAuthenticationProvider
                    {
                        // 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.
                        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            validateInterval: authenticationOptions.CookiesValidateInterval,
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager, authenticationOptions.AuthenticationType))
                    }
                });
            }

            if (authenticationOptions.BearerTokensEnabled)
            {
                container.RegisterType <IRefreshTokenService, RefreshTokenService>();

                var refreshTokenService  = container.Resolve <IRefreshTokenService>();
                var refreshTokenProvider = new RefreshTokenProvider(authenticationOptions.RefreshTokenExpireTimeSpan, refreshTokenService);
                var eventPublisher       = container.Resolve <IEventPublisher>();
                var securityService      = container.Resolve <ISecurityService>();

                app.UseOAuthBearerTokens(new OAuthAuthorizationServerOptions
                {
                    TokenEndpointPath     = new PathString("/Token"),
                    AuthorizeEndpointPath = new PathString("/Account/Authorize"),
                    Provider                  = new ApplicationOAuthProvider(PublicClientId, authenticationOptions, eventPublisher, securityService),
                    RefreshTokenProvider      = refreshTokenProvider,
                    AccessTokenExpireTimeSpan = authenticationOptions.AccessTokenExpireTimeSpan,
                    AllowInsecureHttp         = true
                });
            }

            if (authenticationOptions.HmacEnabled || authenticationOptions.ApiKeysEnabled)
            {
                var apiAccountProvider     = container.Resolve <IApiAccountProvider>();
                var claimsIdentityProvider = container.Resolve <IClaimsIdentityProvider>();
                var cacheManager           = container.Resolve <ICacheManager <object> >();


                if (authenticationOptions.HmacEnabled)
                {
                    app.UseHmacAuthentication(new HmacAuthenticationOptions
                    {
                        ApiCredentialsProvider  = apiAccountProvider,
                        IdentityProvider        = claimsIdentityProvider,
                        CacheManager            = cacheManager,
                        SignatureValidityPeriod = authenticationOptions.HmacSignatureValidityPeriod
                    });
                }

                if (authenticationOptions.ApiKeysEnabled)
                {
                    app.UseApiKeysAuthentication(new ApiKeysAuthenticationOptions
                    {
                        ApiCredentialsProvider   = apiAccountProvider,
                        IdentityProvider         = claimsIdentityProvider,
                        CacheManager             = cacheManager,
                        HttpHeaderName           = authenticationOptions.ApiKeysHttpHeaderName,
                        QueryStringParameterName = authenticationOptions.ApiKeysQueryStringParameterName
                    });
                }
            }

            if (authenticationOptions.AzureAdAuthenticationEnabled)
            {
                // Cookie authentication to temporarily store external authentication data.
                // NOTE: AuthenticationType should not change - it is used internally by ASP.NET external authentication code!
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    AuthenticationMode = AuthenticationMode.Passive
                });

                var authority = authenticationOptions.AzureAdInstance + authenticationOptions.AzureAdTenantId;
                app.UseOpenIdConnectAuthentication(
                    new OpenIdConnectAuthenticationOptions
                {
                    AuthenticationType         = authenticationOptions.AzureAdAuthenticationType,
                    Caption                    = authenticationOptions.AzureAdAuthenticationCaption,
                    ClientId                   = authenticationOptions.AzureAdApplicationId,
                    Authority                  = authority,
                    AuthenticationMode         = AuthenticationMode.Passive,
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
                });
            }

            app.Use <CurrentUserOwinMiddleware>(container.Resolve <Func <ICurrentUser> >());
        }
示例#12
0
 public OAuthProvider([NotNull] ApiConfiguration configuration) : base(configuration)
 {
     OAuthAuthorizationServerProvider = new GrantProvider(Configuration);
     RefreshTokenProvider             = new RefreshTokenProvider(Configuration);
 }
示例#13
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
        }