Exemplo n.º 1
0
        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();

                var tokenDict = QueryStringToDict(oauthTokenResponse);

                string accessToken = null;
                if (tokenDict.ContainsKey("access_token"))
                {
                    accessToken = tokenDict["access_token"];
                }
                else
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                string openIDUri = OpenIDEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken);
                HttpResponseMessage openIDResponse = await _httpClient.GetAsync(openIDUri, Request.CallCancelled);

                openIDResponse.EnsureSuccessStatusCode();
                string openIDString = await openIDResponse.Content.ReadAsStringAsync();

                openIDString = ExtractOpenIDCallbackBody(openIDString);
                JObject openIDInfo = JObject.Parse(openIDString);

                var clientId = openIDInfo["client_id"].Value <string>();
                var openId   = openIDInfo["openid"].Value <string>();

                string userInfoUri = UserInfoEndpoint +
                                     "?access_token=" + Uri.EscapeDataString(accessToken) +
                                     "&oauth_consumer_key=" + Uri.EscapeDataString(clientId) +
                                     "&openid=" + Uri.EscapeDataString(openId);
                HttpResponseMessage userInfoResponse = await _httpClient.GetAsync(userInfoUri, Request.CallCancelled);

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

                JObject userInfo = JObject.Parse(userInfoString);

                var context = new QQConnectAuthenticatedContext(Context, openId, userInfo, 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:qqconnect:id", context.Id, XmlSchemaString, Options.AuthenticationType),
                    new Claim("urn:qqconnect:name", context.Name, XmlSchemaString, Options.AuthenticationType),
                });
                if (!String.IsNullOrWhiteSpace(context.Avatar))
                {
                    var claim_type = string.Format("urn:{0}:avatar", Options.AuthenticationType.ToLower());//"urn:qq:avatar"
                    context.Identity.AddClaim(new Claim(claim_type, context.Avatar, 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));
        }
Exemplo n.º 2
0
 public Task Authenticated(QQConnectAuthenticatedContext context)
 {
     return(onAuthenticated(context));
 }