예제 #1
0
        public override Task Authenticated(SinaWeiboAccountAuthenticatedContext context)
        {
            context.Identity.AddClaim(
                new Claim(ServiceClaimTypes.ProviderAccessToken, context.AccessToken));

            return(base.Authenticated(context));
        }
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            _logger.WriteVerbose("AuthenticateCore");

            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, _logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var tokenRequestParameters = new List <KeyValuePair <string, string> >()
                {
                    new KeyValuePair <string, string>("client_id", Options.AppId),
                    new KeyValuePair <string, string>("client_secret", Options.AppSecret),
                    new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                };

                FormUrlEncodedContent requestContent = new FormUrlEncodedContent(tokenRequestParameters);

                HttpResponseMessage response = await _httpClient.PostAsync(TokenEndpoint, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode();
                string oauthTokenResponse = await response.Content.ReadAsStringAsync();

                JObject oauth2Token = JObject.Parse(oauthTokenResponse);
                string  accessToken = oauth2Token["access_token"].Value <string>();

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                HttpResponseMessage userInfoResponse = await _httpClient.GetAsync(
                    UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) + "&uid=" + oauth2Token["uid"].Value <string>(),
                    Request.CallCancelled);

                userInfoResponse.EnsureSuccessStatusCode();
                string accountString = await userInfoResponse.Content.ReadAsStringAsync();

                JObject accountInfo = JObject.Parse(accountString);

                string email = String.Empty;
                if (Options.RequireEmail)
                {
                    HttpResponseMessage emailResponse = await _httpClient.GetAsync(
                        EmailDetailEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken),
                        Request.CallCancelled);

                    emailResponse.EnsureSuccessStatusCode();
                    string emailString = await emailResponse.Content.ReadAsStringAsync();

                    email = JObject.Parse(accountString)["email"].Value <string>();
                }

                var context = new SinaWeiboAccountAuthenticatedContext(Context, accountInfo, email, accessToken);
                context.Identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:sinaweibo:id", context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:sinaweibo:name", context.Name, XmlSchemaString, Options.AuthenticationType),
                });
                if (!String.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }

                await Options.Provider.Authenticated(context);

                context.Properties = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }

            return(new AuthenticationTicket(null, properties));
        }
예제 #3
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            logger.WriteInformation("AuthenticateCoreAsync::::Start");

            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }

                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }


                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("client_id", Options.AppId));
                body.Add(new KeyValuePair <string, string>("client_secret", Options.AppSecret));

                // Request the token
                HttpResponseMessage tokenResponse =
                    await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                string oauthTokenResponse = await tokenResponse.Content.ReadAsStringAsync();

                // JObject oauth2Token = JObject.Parse(oauthTokenResponse);

                dynamic response    = JsonConvert.DeserializeObject <dynamic>(oauthTokenResponse);
                string  accessToken = (string)response.access_token;
                string  expires     = (string)response.expires_in;
                string  uid         = (string)response.uid;

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    logger.WriteWarning("AuthenticateCoreAsync::::Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                HttpResponseMessage userInfoResponse = await _httpClient.GetAsync(
                    UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) + "&uid=" + uid,
                    Request.CallCancelled);

                userInfoResponse.EnsureSuccessStatusCode();
                string accountString = await userInfoResponse.Content.ReadAsStringAsync();

                JObject accountInfo = JObject.Parse(accountString);

                //string email = String.Empty;
                //if (Options.RequireEmail)
                //{
                //    HttpResponseMessage emailResponse = await _httpClient.GetAsync(
                //        EmailDetailEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken),
                //        Request.CallCancelled);
                //    emailResponse.EnsureSuccessStatusCode();
                //    string emailString = await emailResponse.Content.ReadAsStringAsync();
                //    email = JObject.Parse(accountString)["email"].Value<string>();
                //}

                var context = new SinaWeiboAccountAuthenticatedContext(Context, accountInfo, string.Empty, accessToken);

                context.Identity = new ClaimsIdentity(new[] {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:sinaweibo:id", context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:sinaweibo:name", context.Name, XmlSchemaString, Options.AuthenticationType),
                });


                if (!String.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
                }


                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                logger.WriteInformation("AuthenticateCoreAsync::::return new AuthenticationTicket(context.Identity, context.Properties);");
                logger.WriteInformation("AuthenticateCoreAsync::::End");

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }

            logger.WriteInformation("AuthenticateCoreAsync::::return new AuthenticationTicket(null, properties);");
            logger.WriteInformation("AuthenticateCoreAsync::::END");
            return(new AuthenticationTicket(null, properties));


            #region Old Code
            //logger.WriteInformation("AuthenticateCoreAsync::::Start");

            //AuthenticationProperties properties = null;

            //try
            //{
            //    string code = null;
            //    string state = null;

            //    IReadableStringCollection query = Request.Query;
            //    IList<string> values = query.GetValues("code");
            //    if (values != null && values.Count == 1)
            //    {
            //        code = values[0];
            //    }

            //    values = query.GetValues("state");
            //    if (values != null && values.Count == 1)
            //    {
            //        state = values[0];
            //    }

            //    properties = Options.StateDataFormat.Unprotect(state);



            //    logger.WriteInformation("AuthenticateCoreAsync::::properties:[" + properties + "]");

            //    if (properties == null)
            //    {
            //        logger.WriteInformation("AuthenticateCoreAsync::::return null;");
            //        logger.WriteInformation("AuthenticateCoreAsync::::END");
            //        return null;
            //    }

            //    // OAuth2 10.12 CSRF
            //    if (!ValidateCorrelationId(properties, logger))
            //    {
            //        logger.WriteInformation("AuthenticateCoreAsync::::if (!ValidateCorrelationId(properties, _logger)):return new AuthenticationTicket(null, properties);");
            //        return new AuthenticationTicket(null, properties);
            //    }

            //    var tokenRequestParameters = new List<KeyValuePair<string, string>>()
            //    {
            //        new KeyValuePair<string, string>("client_id", Options.AppId),
            //        new KeyValuePair<string, string>("client_secret", Options.AppSecret),
            //        new KeyValuePair<string, string>("redirect_uri", GenerateRedirectUri()),
            //        new KeyValuePair<string, string>("code", code),
            //        new KeyValuePair<string, string>("grant_type", "authorization_code"),
            //    };

            //    FormUrlEncodedContent requestContent = new FormUrlEncodedContent(tokenRequestParameters);

            //    HttpResponseMessage response = await _httpClient.PostAsync(TokenEndpoint, requestContent, Request.CallCancelled);
            //    response.EnsureSuccessStatusCode();
            //    string oauthTokenResponse = await response.Content.ReadAsStringAsync();

            //    JObject oauth2Token = JObject.Parse(oauthTokenResponse);
            //    string accessToken = oauth2Token["access_token"].Value<string>();

            //    logger.WriteInformation("AuthenticateCoreAsync::::accessToken:[" + accessToken + "]");


            //    if (string.IsNullOrWhiteSpace(accessToken))
            //    {
            //        logger.WriteWarning("AuthenticateCoreAsync::::Access token was not found");
            //        return new AuthenticationTicket(null, properties);
            //    }

            //    HttpResponseMessage userInfoResponse = await _httpClient.GetAsync(
            //        UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) + "&uid=" + oauth2Token["uid"].Value<string>(),
            //        Request.CallCancelled);
            //    userInfoResponse.EnsureSuccessStatusCode();
            //    string accountString = await userInfoResponse.Content.ReadAsStringAsync();
            //    JObject accountInfo = JObject.Parse(accountString);

            //    string email = String.Empty;
            //    if (Options.RequireEmail)
            //    {
            //        HttpResponseMessage emailResponse = await _httpClient.GetAsync(
            //            EmailDetailEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken),
            //            Request.CallCancelled);
            //        emailResponse.EnsureSuccessStatusCode();
            //        string emailString = await emailResponse.Content.ReadAsStringAsync();
            //        email= JObject.Parse(accountString)["email"].Value<string>();
            //    }

            //    var context = new SinaWeiboAccountAuthenticatedContext(Context, accountInfo, email, accessToken);
            //    context.Identity = new ClaimsIdentity(new[]{
            //        new Claim(ClaimTypes.NameIdentifier, context.Id,XmlSchemaString,Options.AuthenticationType),
            //        new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name,XmlSchemaString,Options.AuthenticationType),
            //        new Claim("urn:sinaweibo:id", context.Id,XmlSchemaString,Options.AuthenticationType),
            //        new Claim("urn:sinaweibo:name", context.Name,XmlSchemaString,Options.AuthenticationType),
            //    });
            //    if (!String.IsNullOrWhiteSpace(context.Email))
            //    {
            //        context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
            //    }

            //    await Options.Provider.Authenticated(context);

            //    properties.RedirectUri = GenerateRedirectUri();

            //    context.Properties = properties;



            //    logger.WriteInformation("AuthenticateCoreAsync::::return new AuthenticationTicket(context.Identity, context.Properties);");
            //    logger.WriteInformation("AuthenticateCoreAsync::::END");

            //    return new AuthenticationTicket(context.Identity, context.Properties);
            //}
            //catch (Exception ex)
            //{
            //    logger.WriteError(ex.Message);
            //}

            //logger.WriteInformation("AuthenticateCoreAsync::::return new AuthenticationTicket(null, properties);");
            //logger.WriteInformation("AuthenticateCoreAsync::::END");
            //return new AuthenticationTicket(null, properties);

            #endregion
        }