public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            User user = await this.UserProvider.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", Exceptions.InvalidGrant);
                return;
            }

            OwinHelper.SingIn(context, user);
        }
        public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null)
        {
            if (error != null)
            {
                return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)));
            }

            ExternalLoginProvider loginProvider;

            if (!Enum.TryParse <ExternalLoginProvider>(provider, ignoreCase: true, result: out loginProvider) ||
                loginProvider == ExternalLoginProvider.None)
            {
                //Unsupported login provider
                return(InternalServerError());
            }

            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(loginProvider, this));
            }

            ExternalLoginModel externalLogin = ExternalLoginModel.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            if (externalLogin.Provider != loginProvider)
            {
                Request.GetOwinContext().Authentication.SignOut(
                    DefaultAuthenticationTypes.ExternalCookie,
                    OAuthDefaults.AuthenticationType,
                    CookieAuthenticationDefaults.AuthenticationType);
                return(new ChallengeResult(loginProvider, this));
            }

            User user = await this.UserProvider.FindAsync(externalLogin.Provider, externalLogin.ProviderKey);

            if (user != null)
            {
                OwinHelper.SingIn(Request.GetOwinContext(), user, externalLogin);
            }
            else
            {
                OwinHelper.SingIn(Request.GetOwinContext(), externalLogin);
            }

            return(Ok());
        }
        public async Task <RegistrationResult> RegisterExternal()
        {
            ExternalLoginModel externalLogin = ExternalLoginModel.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                throw new ApiException(Exceptions.ExternalLoginNotFound);
            }

            var user = await this.UserProvider.CreateExternalAsync(externalLogin);

            var userViewModel = UserProvider.MapUserToViewModel(user, externalLogin);

            OwinHelper.SingIn(Request.GetOwinContext(), user, externalLogin);
            var token = OwinHelper.CreateToken(Request.GetOwinContext(), user, externalLogin);

            return(new RegistrationResult(userViewModel, token));
        }