/// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="identity"></param>
        /// <param name="properties"></param>
        /// <param name="tokens"></param>
        /// <returns></returns>
        protected override async Task <AuthenticationTicket> CreateTicketAsync([NotNull] ClaimsIdentity identity, [NotNull] AuthenticationProperties properties, [NotNull] OAuthTokenResponse tokens)
        {
            var requestUser           = new AlipayUserInfoShareRequest();
            var userinfoShareResponse = _alipayClient.Execute(requestUser, tokens.AccessToken);

            if (userinfoShareResponse.IsError)
            {
                Logger.LogError("An error occurred while retrieving the user profile: the remote server " +
                                "returned a {Status} response with the following payload: {Headers} {Body}.",
                                /* Status: */ userinfoShareResponse.Code,
                                /* Headers: */ userinfoShareResponse.Msg,
                                /* Body: */ userinfoShareResponse.Body);

                throw new HttpRequestException("An error occurred while retrieving user information.");
            }
            else
            {
                var payload   = JObject.FromObject(userinfoShareResponse);
                var principal = new ClaimsPrincipal(identity);
                var context   = new OAuthCreatingTicketContext(principal, properties, Context, Scheme, Options, Backchannel, tokens, payload);
                context.RunClaimActions(payload);
                await Options.Events.CreatingTicket(context);

                return(new AuthenticationTicket(context.Principal, context.Properties, Scheme.Name));
            }
        }
示例#2
0
文件: AliPayAPI.cs 项目: qdjx/C5
    public static AlipayUserInfoShareResponse alipay_user_info_share(string accessToken)
    {
        var client = GetAlipayClient();
        AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
        AlipayUserInfoShareResponse response = client.Execute(request, accessToken);

        return(response);
    }
示例#3
0
        /// <summary>
        /// 获取用户的信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task <MyJsonResult> GetUserInfoAsync(string token)
        {
            //构建公共参数
            IAopClient client = new DefaultAopClient(ServerUrl, Appid, PriKey, "json", "1.0", "RSA2", PubKey, null, false);
            AlipayUserInfoShareRequest request = new AlipayUserInfoShareRequest();
            //执行
            AlipayUserInfoShareResponse response = await client.ExecuteAsync(request, token);

            //构建返回的结果
            if (response.Code != "10000")
            {
                myJsonResult.code    = (int)MyJsonResultEnum.thirdError;
                myJsonResult.failMsg = response.SubMsg;
            }
            myJsonResult.rows = response;
            return(myJsonResult);
        }
示例#4
0
 public static m_Alipay_server_UserInfo getUserInfoFromAlipay(string app_id, string token)
 {
     try
     {
         IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", app_id, "\\RSA\\merchant_private_key_2048.txt", "json", "1.0", "RSA2", "\\RSA\\alipay_public_key_sha256.txt", "GBK", true);
         AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
         AlipayUserInfoShareResponse response = client.Execute(request, token);
         var user = JsonConvert.DeserializeObject <m_Alipay_server_UserInfo>(response.Body);
         if (null == user)
         {
             return(null);
         }
         else
         {
             return(user);
         }
     }
     catch (Exception ex)
     {
         //记录日志
     }
     return(null);
 }
示例#5
0
        protected override AuthUser getUserInfo(AuthToken authToken)
        {
            string accessToken = authToken.accessToken;
            AlipayUserInfoShareRequest  request  = new AlipayUserInfoShareRequest();
            AlipayUserInfoShareResponse response = null;

            try
            {
                response = this.aopClient.Execute(request, accessToken);
            }
            catch (Exception e)
            {
                throw new Exception(e.Message, e);
            }
            if (response.IsError)
            {
                throw new Exception(response.SubMsg);
            }

            string province = response.Province, city = response.City;
            string location = string.Format("{0} {1}", !province.IsNullOrWhiteSpace() ? "" : province, !city.IsNullOrWhiteSpace() ? "" : city);

            var authUser = new AuthUser();

            authUser.username        = response.UserName.IsNullOrWhiteSpace() ? response.NickName : response.UserName;
            authUser.nickname        = response.NickName;
            authUser.avatar          = response.Avatar;
            authUser.location        = location;
            authUser.uuid            = response.UserId;
            authUser.gender          = GlobalAuthUtil.getRealGender(response.Gender);
            authUser.token           = authToken;
            authUser.source          = source.getName();
            authUser.originalUser    = response;
            authUser.originalUserStr = JsonConvert.SerializeObject(response);
            return(authUser);
        }
        /// <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));
        }