Пример #1
0
        protected override async Task <bool> HandleUnauthorizedAsync(ChallengeContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var properties = new AuthenticationProperties(context.Properties);

            if (string.IsNullOrEmpty(properties.RedirectUri))
            {
                properties.RedirectUri = CurrentUri;
            }

            var tenantOptions = new MultiTenantTwitterOptionsResolver(Options, siteResolver, siteRepo, multiTenantOptions);

            //var requestToken = await ObtainRequestTokenAsync(
            //    Options.ConsumerKey,
            //    Options.ConsumerSecret,
            //    BuildRedirectUri(Options.CallbackPath),
            //    properties);

            var requestToken = await ObtainRequestTokenAsync(
                tenantOptions.ConsumerKey,
                tenantOptions.ConsumerSecret,
                BuildRedirectUri(tenantOptions.ResolveRedirectUrl(Options.CallbackPath)),
                properties);

            if (requestToken.CallbackConfirmed)
            {
                var twitterAuthenticationEndpoint = AuthenticationEndpoint + requestToken.Token;

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsHttps
                };

                Response.Cookies.Append(
                    tenantOptions.ResolveStateCookieName(StateCookie),
                    Options.StateDataFormat.Protect(requestToken),
                    cookieOptions);

                var redirectContext = new TwitterRedirectToAuthorizationEndpointContext(
                    Context, Options,
                    properties, twitterAuthenticationEndpoint);

                await Options.Events.RedirectToAuthorizationEndpoint(redirectContext);

                return(true);
            }
            else
            {
                Logger.LogError("requestToken CallbackConfirmed!=true");
            }
            return(false); // REVIEW: Make sure this should not stop other handlers
        }
Пример #2
0
        //public async Task<bool> InvokeReturnPathAsync()
        //{
        //    var model = await HandleAuthenticateOnceAsync();
        //    if (model == null)
        //    {
        //        Logger.LogWarning("Invalid return state, unable to redirect.");
        //        Response.StatusCode = 500;
        //        return true;
        //    }

        //    var context = new SigningInContext(Context, model)
        //    {
        //        SignInScheme = Options.SignInScheme,
        //        RedirectUri = model.Properties.RedirectUri
        //    };
        //    model.Properties.RedirectUri = null;

        //    await Options.Events.SigningIn(context);

        //    if (context.SignInScheme != null && context.Principal != null)
        //    {
        //        await Context.Authentication.SignInAsync(context.SignInScheme, context.Principal, context.Properties);
        //    }

        //    if (!context.IsRequestCompleted && context.RedirectUri != null)
        //    {
        //        if (context.Principal == null)
        //        {
        //            // add a redirect hint that sign-in failed in some way
        //            context.RedirectUri = QueryHelpers.AddQueryString(context.RedirectUri, "error", "access_denied");
        //        }
        //        Response.Redirect(context.RedirectUri);
        //        context.RequestCompleted();
        //    }

        //    return context.IsRequestCompleted;
        //}

        protected override async Task <AuthenticateResult> HandleRemoteAuthenticateAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                var currentSite = await GetSite();

                var tenantOptions = new MultiTenantTwitterOptionsResolver(
                    Options,
                    currentSite,
                    multiTenantOptions);

                var query = Request.Query;
                var protectedRequestToken = Request.Cookies[tenantOptions.ResolveStateCookieName(StateCookie)];

                var requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);

                if (requestToken == null)
                {
                    Logger.LogWarning("Invalid state");
                    return(AuthenticateResult.Failed("Invalid state cookie."));
                }

                properties = requestToken.Properties;

                var returnedToken = query["oauth_token"];
                //if (StringValues.IsNullOrEmpty(returnedToken))
                if (string.IsNullOrEmpty(returnedToken))
                {
                    Logger.LogWarning("Missing oauth_token");
                    //return new AuthenticationTicket(properties, Options.AuthenticationScheme);
                    return(AuthenticateResult.Failed("Missing oauth_token"));
                }

                if (!string.Equals(returnedToken, requestToken.Token, StringComparison.Ordinal))
                {
                    Logger.LogWarning("Unmatched token");
                    //return new AuthenticationTicket(properties, Options.AuthenticationScheme);
                    return(AuthenticateResult.Failed("Unmatched token"));
                }

                var oauthVerifier = query["oauth_verifier"];
                //if (StringValues.IsNullOrEmpty(oauthVerifier))
                if (string.IsNullOrEmpty(oauthVerifier))
                {
                    Logger.LogWarning("Missing or blank oauth_verifier");
                    //return new AuthenticationTicket(properties, Options.AuthenticationScheme);
                    return(AuthenticateResult.Failed("Missing or blank oauth_verifier"));
                }

                var cookieOptions = new CookieOptions
                {
                    HttpOnly = true,
                    Secure   = Request.IsHttps
                };

                Response.Cookies.Delete(tenantOptions.ResolveStateCookieName(StateCookie), cookieOptions);



                //var accessToken = await ObtainAccessTokenAsync(
                //    Options.ConsumerKey,
                //    Options.ConsumerSecret,
                //    requestToken,
                //    oauthVerifier);

                var accessToken = await ObtainAccessTokenAsync(
                    tenantOptions.ConsumerKey,
                    tenantOptions.ConsumerSecret,
                    requestToken,
                    oauthVerifier);

                var identity = new ClaimsIdentity(new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim(ClaimTypes.Name, accessToken.ScreenName, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim("urn:twitter:userid", accessToken.UserId, ClaimValueTypes.String, Options.ClaimsIssuer),
                    new Claim("urn:twitter:screenname", accessToken.ScreenName, ClaimValueTypes.String, Options.ClaimsIssuer)
                },
                                                  Options.ClaimsIssuer);

                if (Options.SaveTokensAsClaims)
                {
                    identity.AddClaim(new Claim("access_token", accessToken.Token, ClaimValueTypes.String, Options.ClaimsIssuer));
                }

                //return await CreateTicketAsync(identity, properties, accessToken);
                return(AuthenticateResult.Success(await CreateTicketAsync(identity, properties, accessToken)));
            }
            catch (Exception ex)
            {
                Logger.LogError("Authentication failed", ex);
                //return new AuthenticationTicket(properties, Options.AuthenticationScheme);
                return(AuthenticateResult.Failed("Authentication failed, exception logged"));
            }
        }