/// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

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

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("auth_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));
                }

                // Check for error
                if (Request.Query.Get("error") != null)
                {
                    return(new AuthenticationTicket(null, properties));
                }

                var alipayRequest = new AlipaySystemOauthTokenRequest
                {
                    Code      = code,
                    GrantType = "authorization_code"
                                //GetApiName()
                };

                AlipaySystemOauthTokenResponse alipayResponse = _alipayClient.Execute(alipayRequest);
                if (alipayResponse.IsError)
                {
                    _logger.WriteWarning("An error occurred while retrieving an access token.");
                    return(new AuthenticationTicket(null, properties));
                }
                else
                {
                    // Request the token
                    //var response = JObject.Parse(alipayResponse.Body);
                    //dynamic tokens = new
                    //{
                    //    Response = response,
                    //    AccessToken = response["alipay_system_oauth_token_response"].Value<string>("access_token"),
                    //    TokenType = response["alipay_system_oauth_token_response"].Value<string>("token_type"),
                    //    RefreshToken = response["alipay_system_oauth_token_response"].Value<string>("refresh_token"),
                    //    ExpiresIn = response["alipay_system_oauth_token_response"].Value<string>("expires_in")
                    //};
                    //var Response = response;
                    //var AccessToken = alipayResponse.AccessToken;
                    //var TokenType = response.Value<string>("token_type");
                    //var RefreshToken = response.alipay_system_oauth_token_response.expires_in;
                    //var ExpiresIn = response.Value<string>("expires_in");


                    // Get the Alipay user
                    var requestUser = new AlipayUserInfoShareRequest();
                    AlipayUserInfoShareResponse userinfoShareResponse = _alipayClient.Execute(requestUser, alipayResponse.AccessToken);
                    if (userinfoShareResponse.IsError)
                    {
                        _logger.WriteWarning("An error occurred while retrieving user information.");
                        throw new HttpRequestException("An error occurred while retrieving user information.");
                    }
                    else
                    {
                        //var user = JObject.FromObject(userinfoShareResponse);
                        var context = new AlipayAuthenticatedContext(Context, userinfoShareResponse, alipayResponse.AccessToken, Convert.ToInt32(alipayResponse.ExpiresIn))
                        {
                            Identity = new ClaimsIdentity(
                                Options.AuthenticationType,
                                ClaimsIdentity.DefaultNameClaimType,
                                ClaimsIdentity.DefaultRoleClaimType)
                        };
                        if (!string.IsNullOrEmpty(context.UserId))
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                        }
                        if (!string.IsNullOrEmpty(context.UserName))
                        {
                            context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                        }
                        context.Properties = properties;

                        await Options.Provider.Authenticated(context);

                        return(new AuthenticationTicket(context.Identity, context.Properties));
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
コード例 #2
0
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            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));
                }

                // Check for error
                if (Request.Query.Get("error") != null)
                {
                    return(new AuthenticationTicket(null, properties));
                }

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

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

                // Request the token
                var tokenResponse =
                    await _httpClient.PostAsync(Options.TokenEndPoint, new FormUrlEncodedContent(body));

                tokenResponse.EnsureSuccessStatusCode();
                var text = await tokenResponse.Content.ReadAsStringAsync();

                // Deserializes the token response
                dynamic response = JsonConvert.DeserializeObject <dynamic>(text);
                if (response == null || response.access_token == null)
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }
                var accessToken = (string)response.access_token;

                // Get the Alipay user
                //
                var userResponse = await _httpClient.GetAsync(
                    Options.UserInfoEndPoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                userResponse.EnsureSuccessStatusCode();
                text = await userResponse.Content.ReadAsStringAsync();

                var user = JObject.Parse(text);

                var context = new AlipayAuthenticatedContext(Context, user, accessToken)
                {
                    Identity = new ClaimsIdentity(
                        Options.AuthenticationType,
                        ClaimsIdentity.DefaultNameClaimType,
                        ClaimsIdentity.DefaultRoleClaimType)
                };
                if (!string.IsNullOrEmpty(context.UserId))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType));
                    context.Identity.AddClaim(new Claim(Claims.UserId, context.UserId, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                    context.Identity.AddClaim(new Claim(Claims.NickName, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
 /// <summary>
 /// Invoked whenever Alipay successfully authenticates a user
 /// </summary>
 /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
 /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
 public virtual Task Authenticated(AlipayAuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }