Beispiel #1
0
        /// <summary>
        /// 获取授权连接
        /// </summary>
        /// <param name="appId">公众号的appid</param>
        /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址</param>
        /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节</param>
        /// <param name="componentAppid">服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到</param>
        /// <param name="responseType">默认为填code</param>
        /// <returns>URL</returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, OAuthScope scope, string state, string componentAppid, string responseType = "code")
        {
            var url =
                $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={appId}&redirect_uri={redirectUrl.UrlEncode()}&response_type={responseType}&scope={scope}&state={state}&component_appid={componentAppid}#wechat_redirect";

            return(url);
        }
Beispiel #2
0
        /// <summary>
        /// 第一步:生成网页授权访问地址
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="redirectUrl"></param>
        /// <param name="state"></param>
        /// <param name="scope"></param>
        /// <param name="responseType"></param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId,string redirectUrl,string state,OAuthScope scope,string responseType = "code")
        {
            var url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                appId, System.Web.HttpUtility.UrlEncode(redirectUrl), responseType, scope, state);

            return url;
        }
        internal static string Build(OAuthScope oauthScope)
        {
            if (oauthScope == OAuthScope.none)
            {
                return string.Empty;
            }

            var shopifyScopeStringBuilder = new StringBuilder();
            foreach (var item in Enum.GetValues(typeof(OAuthScope)))
            {
                var shopifyScopeItem = (OAuthScope)item;
                if (shopifyScopeItem == OAuthScope.none || (oauthScope & shopifyScopeItem) != shopifyScopeItem)
                {
                    continue;
                }

                shopifyScopeStringBuilder.Append(shopifyScopeItem.ToString().ToLowerInvariant());
                shopifyScopeStringBuilder.Append(',');
            }

            if (shopifyScopeStringBuilder.Length > 0 && shopifyScopeStringBuilder[shopifyScopeStringBuilder.Length - 1] == ',')
            {
                return shopifyScopeStringBuilder.ToString().Substring(0, shopifyScopeStringBuilder.Length - 1);
            }

            return shopifyScopeStringBuilder.ToString();
        }
Beispiel #4
0
        public static string GetOAuthUrl(string appId, string redirectUriHTTPS, OAuthScope scope, string state)
        {
            string url = string.Format(OAuthUrlTemplate, appId, HttpUtility.UrlEncode(redirectUriHTTPS), scope.ToString(), state);

            WechatLib.WriteLog("OAuthUrl converted:" + url);
            return(url);
        }
Beispiel #5
0
        internal static string Build(OAuthScope oauthScope)
        {
            if (oauthScope == OAuthScope.none)
            {
                return(string.Empty);
            }

            var shopifyScopeStringBuilder = new StringBuilder();

            foreach (var item in Enum.GetValues(typeof(OAuthScope)))
            {
                var shopifyScopeItem = (OAuthScope)item;
                if (shopifyScopeItem == OAuthScope.none || (oauthScope & shopifyScopeItem) != shopifyScopeItem)
                {
                    continue;
                }

                shopifyScopeStringBuilder.Append(shopifyScopeItem.ToString().ToLowerInvariant());
                shopifyScopeStringBuilder.Append(',');
            }

            if (shopifyScopeStringBuilder.Length > 0 && shopifyScopeStringBuilder[shopifyScopeStringBuilder.Length - 1] == ',')
            {
                return(shopifyScopeStringBuilder.ToString().Substring(0, shopifyScopeStringBuilder.Length - 1));
            }

            return(shopifyScopeStringBuilder.ToString());
        }
Beispiel #6
0
 /// <summary>
 /// 根据 code 获取  openid ,如果获取到 openid ,返回 openid;
 /// 如果获取不到,返回错误标记和 给定 Url 的 微信的授权登录验证页面的Url
 /// </summary>
 /// <returns></returns>
 public (bool hasOpenId, string openIdOrUrl) GetWechatOpenIdOrAuthenUrl(
     string code,
     string redirectUrl,
     OAuthScope authType = OAuthScope.snsapi_base)
 {
     if (string.IsNullOrEmpty(code))
     {
         return(false, Config.GetAuthenUrl(redirectUrl, authType));;
     }
     else
     {
         var result = this.GetOpenIdInfoAccordCode(code);
         if (result == null)
         {
             return(false, Config.GetAuthenUrl(redirectUrl, authType));;
         }
         else
         {
             if (result.errcode == Senparc.Weixin.ReturnCode.请求成功)
             {
                 return(true, result.openid);
             }
             else
             {
                 return(false, Config.GetAuthenUrl(redirectUrl, authType));
             }
         }
     }
 }
Beispiel #7
0
        /// <summary>
        /// 获取授权连接
        /// </summary>
        /// <param name="appId">公众号的appid</param>
        /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址</param>
        /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节</param>
        /// <param name="component_appid">服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到</param>
        /// <param name="responseType">默认为填code</param>
        /// <returns>URL</returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, OAuthScope scope, string state, string component_appid, string responseType = "code")
        {
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}&component_appid={5}#wechat_redirect",
                              appId, redirectUrl.UrlEncode(), responseType, scope, state, component_appid);

            return(url);
        }
Beispiel #8
0
        public string GetWechatAuthorizeUrl(string redirectUrl, string state, OAuthScope oAuthScope)
        {
            CacheHelper.SetCache("State", state);
            string wxAuthorizeUrl = OAuthApi.GetAuthorizeUrl(_appid, redirectUrl, state, oAuthScope);

            LogHelper.Logger.Debug(string.Format("要回调的地址为:{0}获取到微信授权服务器的地址为:{1}", redirectUrl, wxAuthorizeUrl));
            return(wxAuthorizeUrl);
        }
Beispiel #9
0
 private static JObject ToDto(OAuthScope scope)
 {
     return(new JObject
     {
         { "name", scope.Name },
         { "is_exposed", scope.IsExposedInConfigurationEdp },
         { "update_datetime", scope.UpdateDateTime },
         { "create_datetime", scope.CreateDateTime }
     });
 }
        public async new Task <dynamic> Register(string client_name, OAuthScope scopes, string redirect_uris = "urn:ietf:wg:oauth:2.0:oob", string website = null)
        {
            var response = await base.Register(client_name, scopes, redirect_uris, website);

            var json = DynamicJson.Parse(response.Content);

            json.auth_url = OAuthUrl(_Host, json.client_id, scopes, redirect_uris);

            return(json);
        }
Beispiel #11
0
 public void ShouldReturnCorrectAuthUrlFourScopes()
 {
     OAuthScope[] scopes = new OAuthScope[] { OAuthScope.FilesRead, OAuthScope.FilesWrite, OAuthScope.ACLInvitations, OAuthScope.UserPassword };
     var uri = Client.GenerateAuthorizationUrl(scopes);
     var expect =
         String.Format("{0}/authorize?response_type=code", Settings.HostName) +
         String.Format("&client_id={0}", Settings.ClientID) +
         String.Format("&redirect_uri={0}", Settings.RedirectUri) +
         String.Format("&scope={0}", "files.read,files.write,acl.invitations,user.password");
     Assert.AreEqual(expect, uri);
 }
Beispiel #12
0
 public static JObject ToDto(this OAuthScope scope)
 {
     return(new JObject
     {
         { OAuthScopeParameters.Name, scope.Name },
         { OAuthScopeParameters.IsExposed, scope.IsExposedInConfigurationEdp },
         { OAuthScopeParameters.IsStandard, scope.IsStandardScope },
         { OAuthScopeParameters.UpdateDateTime, scope.UpdateDateTime },
         { OAuthScopeParameters.CreateDateTime, scope.CreateDateTime },
         { OAuthScopeParameters.Claims, new JArray(scope.Claims.Select(c => c.ClaimName).ToArray()) }
     });
 }
Beispiel #13
0
        /// <summary>
        /// 获取验证地址
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="redirectUrl"></param>
        /// <param name="state"></param>
        /// <param name="scope"></param>
        /// <param name="responseType"></param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code")
        {
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                                appId, redirectUrl.UrlEncode(), responseType, scope, state);

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用)
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return url;
        }
Beispiel #14
0
       /*此接口不提供异步方法*/
        /// <summary>
        /// 获取验证地址
        /// </summary>
        /// <param name="appId">公众号的appid</param>
        /// <param name="componentAppId">第三方平台的appid</param>
        /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节</param>
        /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔。此处暂时只放一作用域。</param>
        /// <param name="responseType">默认,填code</param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId, string componentAppId, string redirectUrl, string state, OAuthScope[] scopes, string responseType = "code")
        {
            //此URL比MP中的对应接口多了&component_appid=component_appid参数
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}&component_appid={5}#wechat_redirect",
                                appId.AsUrlData(), redirectUrl.AsUrlData(), responseType.AsUrlData(), string.Join(",", scopes.Select(z => z.ToString())).AsUrlData(), state.AsUrlData(), componentAppId.AsUrlData());

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 如果用户同意授权,页面将跳转至 redirect_uri?code=CODE&state=STATE&appid=APPID。这里的code用于换取access_token(和通用接口的access_token不通用)
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return url;
        }
        public async Task <AppRegistration> Register(string client_name, OAuthScope scopes, string redirect_uris = "urn:ietf:wg:oauth:2.0:oob", string website = null)
        {
            var response = await Execute <AppRegistration>(nameof(Register),
                                                           new { client_name, redirect_uris, scopes, website });

            response.Data.AuthUrl = OAuthUrl(response.Data.ClientId, scopes, response.Data.RedirectUri);

            response.Data.Scope = scopes;

            response.Data.Instance = _Host;

            return(response.Data);
        }
Beispiel #16
0
        /// <summary>
        /// 微信扫码登录网页授权
        /// </summary>
        /// <param name="appId">第三方应用唯一标识</param>
        /// <param name="redirectUrl">重定向地址,需要进行UrlEncode</param>
        /// <param name="state">用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验</param>
        /// <param name="scopes">应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login即可</param>
        /// <param name="responseType">填code</param>
        /// <returns></returns>
        public static string GetQRConnectUrl(string appId, string redirectUrl, string state, OAuthScope[] scopes, string responseType = "code")
        {
            //此URL比MP中的对应接口多了&component_appid=component_appid参数
            var url =
                string.Format("https://open.weixin.qq.com/connect/qrconnect?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                                appId, redirectUrl.UrlEncode(), responseType, string.Join(",", scopes.Select(z => z.ToString())), state);

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code和state参数redirect_uri?code=CODE&state=STATE
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return url;
        }
Beispiel #17
0
        /// <summary>
        /// 获取OAuth授权的Url地址。
        /// </summary>
        /// <param name="url">需要跳转的目标地址。</param>
        /// <param name="scope">OAuth域。</param>
        /// <param name="state">状态参数。</param>
        /// <returns>绝对的Url地址。</returns>
        public string GetAuthorizeUrl(string url, OAuthScope scope, string state = null)
        {
            var appId       = _accountModel.AppId;
            var redirectUrl =
                string.Format(
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}",
                    appId, url, "snsapi_" + scope.ToString().ToLower(), state);

            if (_openAccountModel != null)
            {
                redirectUrl = redirectUrl + "&component_appid=" + _openAccountModel.AppId;
            }
            return(redirectUrl + "#wechat_redirect");
        }
Beispiel #18
0
        /// <summary>
        /// 获取验证地址
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="redirectUrl"></param>
        /// <param name="state"></param>
        /// <param name="scope"></param>
        /// <param name="responseType"></param>
        /// <param name="addConnectRedirect">加上后可以解决40029-invalid code的问题(测试中)</param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code",bool addConnectRedirect=true)
        {
            //TODO:addConnectRedirect测试成功后可以推广到Open和QY
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}{5}#wechat_redirect",
                                appId.AsUrlData(), redirectUrl.AsUrlData(), responseType.AsUrlData(), scope.ToString("g").AsUrlData(), state.AsUrlData(),
                                addConnectRedirect? "&connect_redirect=1":"");

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用)
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return url;
        }
        public async new Task <AppRegistration> Register(string client_name, OAuthScope scopes, string redirect_uris = "urn:ietf:wg:oauth:2.0:oob", string website = null)
        {
            var response = await base.Register(client_name, scopes, redirect_uris, website);

            var appRegistration = JsonConvert.DeserializeObject <AppRegistration>(response.Content);

            appRegistration.Instance = _Host;

            appRegistration.Scope = scopes;

            appRegistration.AuthUrl = OAuthUrl(_Host, appRegistration.ClientId, scopes, appRegistration.RedirectUri);

            return(appRegistration);
        }
Beispiel #20
0
        /// <summary>
        /// 获取验证地址
        /// 返回说明:
        /// 用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code, state以及appid(redirect_uri?code=CODE&state=STATE&appid=APPID)
        /// 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数(redirect_uri?state=STATE)
        /// </summary>
        /// <param name="appId">公众号的appid</param>
        /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节</param>
        /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔</param>
        /// <param name="componentAppId">服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到</param>
        /// <param name="responseType">填code</param>
        /// <returns></returns>
        public static string GetOpenAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope,string componentAppId, string responseType = "code")
        {
            /* 在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(一般而言,已微信认证的服务号拥有snsapi_base和snsapi_userinfo),
             * 使用微信客户端打开以下链接(严格按照以下格式,包括顺序和大小写,并请将参数替换为实际内容)
             * 若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
             */

            var url =
                string.Format(
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}&component_appid={5}#wechat_redirect",
                    appId, redirectUrl.UrlEncode(), responseType, scope, state, componentAppId);

            return url;
        }
Beispiel #21
0
        public async Task TestRegister()
        {
            var client = new MastodonDynamicClient(_Host, _AccessToken);

            var result = await client.Register("MastodonClient", OAuthScope.of(Scope.Read, Scope.Write, Scope.Follow));

            Assert.IsNotNull(result.id);

            Assert.IsNotNull(result.client_id);

            Assert.IsNotNull(result.client_secret);

            Assert.IsNotNull(result.auth_url);

            Process.Start((string)result.auth_url);
        }
        public async Task <bool> CheckScopesAreValid(string scope)
        {
            if (string.IsNullOrWhiteSpace(scope))
            {
                return(true); // Unlike the other checks, an empty scope is a valid scope. It just means the application has default permissions.
            }

            string[] scopes = scope.Split(' ');
            foreach (string s in scopes)
            {
                if (!OAuthScope.NameInScopes(s))
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #23
0
        private async Task <AuthorizeViewModel> FillFromRequest(OpenIdConnectRequest OIDCRequest)
        {
            string      clientId = OIDCRequest.ClientId;
            OAuthClient client   = await _context.ClientApplications.FindAsync(clientId);

            if (client == null)
            {
                return(null);
            }
            else
            {
                // Get the Scopes for this application from the query - disallow duplicates
                ICollection <OAuthScope> scopes = new HashSet <OAuthScope>();
                if (!String.IsNullOrWhiteSpace(OIDCRequest.Scope))
                {
                    foreach (string s in OIDCRequest.Scope.Split(' '))
                    {
                        if (OAuthScope.NameInScopes(s))
                        {
                            OAuthScope scope = OAuthScope.GetScope(s);
                            if (!scopes.Contains(scope))
                            {
                                scopes.Add(scope);
                            }
                        }
                        else
                        {
                            return(null);
                        }
                    }
                }

                AuthorizeViewModel avm = new AuthorizeViewModel()
                {
                    ClientId     = OIDCRequest.ClientId,
                    ResponseType = OIDCRequest.ResponseType,
                    State        = OIDCRequest.State,
                    Scopes       = String.IsNullOrWhiteSpace(OIDCRequest.Scope) ? new string[0] : OIDCRequest.Scope.Split(' '),
                    RedirectUri  = OIDCRequest.RedirectUri
                };

                return(avm);
            }
        }
Beispiel #24
0
        public async Task <string> Handle(JObject jObj, CancellationToken cancellationToken)
        {
            var extractedScope = jObj.ToScopeDomain();
            var result         = await _oauthScopeRepository.GetOAuthScope(extractedScope.Name, cancellationToken);

            if (result != null)
            {
                _logger.LogError($"the scope '{extractedScope.Name}' already exists");
                throw new OAuthException(ErrorCodes.INVALID_REQUEST, string.Format(ErrorMessages.SCOPE_ALREADY_EXISTS, extractedScope.Name));
            }

            var scope = OAuthScope.Create(extractedScope.Name);
            await _oauthScopeRepository.Add(scope, cancellationToken);

            await _oauthScopeRepository.SaveChanges(cancellationToken);

            _logger.LogInformation($"the scope '{extractedScope.Name}' has been added");
            return(extractedScope.Name);
        }
Beispiel #25
0
        public async Task TestRegister()
        {
            var client = new MastodonSharpClient(_Host, _AccessToken);

            var result = await client.Register("MastodonClient", OAuthScope.of(Scope.Read, Scope.Write, Scope.Follow));

            Assert.IsNotNull(result.Id);

            Assert.IsNotNull(result.ClientId);

            Assert.IsNotNull(result.ClientSecret);

            Assert.IsNotNull(result.AuthUrl);

            Assert.IsNotNull(result.RedirectUri);

            Assert.IsNotNull(result.Scope);

            Assert.IsNotNull(result.Instance);
        }
Beispiel #26
0
        /// <summary>
        /// Get URL to use for redirection at SHOPIFY OAUTH 2.0 authorization server, asking for permission to access intended store.
        /// </summary>
        /// <param name="shopName">Authorization shop name (w/o '.myshopify.com', only shop name). In case it contains '.myshopify.com' then it would be trimmed out to continue</param>
        /// <param name="scope">SHOPIFY OAUTH 2.0 permission scope(s) for which store admin  will be asked permission for.</param>
        /// <returns>Returns instance of URL that can be used to redirect your current request to initiate SHOPIFY authentication / authorization process.</returns>
        /// <exception cref="ArgumentNullException">Throws argument null exception if input parameters are null or empty.</exception>
        public string GetOAuthUrl(string shopName, OAuthScope scope)
        {
            if (string.IsNullOrEmpty(shopName))
            {
                throw new ArgumentNullException("shopName");
            }

            if (shopName.EndsWith(AppResources.MyShopifyDomain, StringComparison.InvariantCulture))
            {
                var indexOfShopifyDomain = shopName.IndexOf(AppResources.MyShopifyDomain, StringComparison.InvariantCulture);
                shopName = shopName.Substring(0, indexOfShopifyDomain);
            }

            return(string.Format(
                       CultureInfo.InvariantCulture,
                       AppResources.AuthorizationUrl,
                       shopName,
                       this.Configuration.ApiKey,
                       ScopeBuilder.Build(scope)));
        }
Beispiel #27
0
        /// <summary>
        /// 获取验证地址
        /// 返回说明:
        /// 用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code, state以及appid(redirect_uri?code=CODE&state=STATE&appid=APPID)
        /// 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数(redirect_uri?state=STATE)
        /// </summary>
        /// <param name="appId">公众号的appid</param>
        /// <param name="redirectUrl">重定向地址,需要urlencode,这里填写的应是服务开发方的回调地址</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写任意参数值,最多128字节</param>
        /// <param name="scope">授权作用域,拥有多个作用域用逗号(,)分隔</param>
        /// <param name="componentAppId">服务方的appid,在申请创建公众号服务成功后,可在公众号服务详情页找到</param>
        /// <param name="responseType">填code</param>
        /// <returns></returns>
        public static string GetOpenAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string componentAppId, string responseType = "code")
        {
            /* 在确保微信公众账号拥有授权作用域(scope参数)的权限的前提下(一般而言,已微信认证的服务号拥有snsapi_base和snsapi_userinfo),
             * 使用微信客户端打开以下链接(严格按照以下格式,包括顺序和大小写,并请将参数替换为实际内容)
             * 若提示“该链接无法访问”,请检查参数是否填写错误,是否拥有scope参数对应的授权作用域权限。
             */

            var url =
                string.Format(
                    "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}&component_appid={5}#wechat_redirect",
                    appId, redirectUrl.UrlEncode(), responseType, scope, state, componentAppId);

            return(url);
        }
Beispiel #28
0
 /// <summary>
 /// 获取授权url
 /// </summary>
 /// <param name="callbackUrl"></param>
 /// <param name="oAuthScope"></param>
 /// <returns></returns>
 public static string GetAuthorizeUserInfoUrl(string callbackUrl, OAuthScope oAuthScope = OAuthScope.snsapi_base)
 {
     return(OAuth.GetAuthorizeUrl(AppId, callbackUrl, State, oAuthScope));
 }
Beispiel #29
0
 /// <summary>
 /// AppId
 /// </summary>
 /// <param name="appId"></param>
 /// <param name="oauthCallbackUrl">网站内路径(如:/TenpayV3/OAuthCallback),以/开头!当前页面地址会加在Url中的returlUrl=xx参数中</param>
 /// <param name="oauthScope">默认为 OAuthScope.snsapi_userinfo</param>
 public SenparcOAuthAttribute(string appId, string oauthCallbackUrl, OAuthScope oauthScope = OAuthScope.snsapi_userinfo)
 {
     _appId            = appId;
     _oauthCallbackUrl = oauthCallbackUrl;
     _oauthScope       = oauthScope;
 }
Beispiel #30
0
        protected virtual async Task <JwsPayload> BuildIdToken(HandlerContext currentContext, JObject queryParameters, IEnumerable <string> requestedScopes, CancellationToken cancellationToken)
        {
            var openidClient = (OpenIdClient)currentContext.Client;
            var result       = new JwsPayload
            {
                { OAuthClaims.Audiences, new [] { openidClient.ClientId, currentContext.Request.IssuerName } },
                { OAuthClaims.Issuer, currentContext.Request.IssuerName },
                { OAuthClaims.Iat, DateTime.UtcNow.ConvertToUnixTimestamp() },
                { OAuthClaims.ExpirationTime, DateTime.UtcNow.AddSeconds(openidClient.TokenExpirationTimeInSeconds).ConvertToUnixTimestamp() },
                { OAuthClaims.Azp, openidClient.ClientId }
            };
            var maxAge             = queryParameters.GetMaxAgeFromAuthorizationRequest();
            var nonce              = queryParameters.GetNonceFromAuthorizationRequest();
            var acrValues          = queryParameters.GetAcrValuesFromAuthorizationRequest();
            var requestedClaims    = queryParameters.GetClaimsFromAuthorizationRequest();
            var subjectTypeBuilder = _subjectTypeBuilders.First(f => f.SubjectType == (string.IsNullOrWhiteSpace(openidClient.SubjectType) ? PublicSubjectTypeBuilder.SUBJECT_TYPE : openidClient.SubjectType));
            var subject            = await subjectTypeBuilder.Build(currentContext, cancellationToken);

            string accessToken, code;

            if (currentContext.Response.TryGet(OAuth.DTOs.AuthorizationResponseParameters.AccessToken, out accessToken))
            {
                result.Add(OAuthClaims.AtHash, ComputeHash(accessToken));
            }

            if (currentContext.Response.TryGet(OAuth.DTOs.AuthorizationResponseParameters.Code, out code))
            {
                result.Add(OAuthClaims.CHash, ComputeHash(code));
            }

            if (maxAge != null)
            {
                result.Add(OAuthClaims.AuthenticationTime, currentContext.User.GetActiveSession().AuthenticationDateTime.ConvertToUnixTimestamp());
            }

            if (!string.IsNullOrWhiteSpace(nonce))
            {
                result.Add(OAuthClaims.Nonce, nonce);
            }

            var defaultAcr = await _amrHelper.FetchDefaultAcr(acrValues, requestedClaims, openidClient, cancellationToken);

            if (defaultAcr != null)
            {
                result.Add(OAuthClaims.Amr, defaultAcr.AuthenticationMethodReferences);
                result.Add(OAuthClaims.Acr, defaultAcr.Name);
            }

            IEnumerable <OAuthScope> scopes = new OAuthScope[1] {
                SIDOpenIdConstants.StandardScopes.OpenIdScope
            };
            var responseTypes = queryParameters.GetResponseTypesFromAuthorizationRequest();

            if (responseTypes.Count() == 1 && responseTypes.First() == AuthorizationResponseParameters.IdToken)
            {
                scopes = openidClient.AllowedScopes.Where(s => requestedScopes.Any(r => r == s.Name));
            }

            result.Add(OAuthClaims.Sid, currentContext.User.GetActiveSession().SessionId);
            EnrichWithScopeParameter(result, scopes, currentContext.User, subject);
            _claimsJwsPayloadEnricher.EnrichWithClaimsParameter(result, requestedClaims, currentContext.User, currentContext.User.GetActiveSession().AuthenticationDateTime);
            foreach (var claimsSource in _claimsSources)
            {
                await claimsSource.Enrich(result, openidClient, cancellationToken);
            }

            return(result);
        }
 public CustomOAuthAttribute(string appId = null, string oauthCallbackUrl = null, OAuthScope oauthScope = OAuthScope.snsapi_userinfo)
 {
     _appId            = appId ?? WeixinConfig.AppId;
     _oauthCallbackUrl = oauthCallbackUrl ?? WeixinConfig.WeixinOAuthCallbackUrl;
     _oauthScope       = oauthScope;
 }
Beispiel #32
0
        /// <summary>
        /// 第一步:生成网页授权访问地址
        /// </summary>
        /// <param name="appId">公众号的唯一标识</param>
        /// <param name="redirectUrl">授权后重定向的回调链接地址,请使用urlencode对链接进行处理</param>
        /// <param name="state">重定向后会带上state参数,可以填写a-zA-Z0-9的参数值</param>
        /// <param name="scope">应用授权作用域</param>
        /// <param name="responseType">返回类型,目前只有code一种</param>
        /// <returns>网页授权访问地址,引导关注者打开该地址进入网页授权</returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code")
        {
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}#wechat_redirect",
                              appId, System.Web.HttpUtility.UrlEncode(redirectUrl), responseType, scope, state);

            return(url);
        }
Beispiel #33
0
 public static string GetAuthorizeUrl(string redirectUrl, OAuthScope oAuthScope = OAuthScope.snsapi_base)
 {
     return OAuthApi.GetAuthorizeUrl(WebSettingHelper.WxAppId, redirectUrl, "state", oAuthScope);
 }
 /// <summary>
 /// 获取验证地址
 /// </summary>
 public string GetAuthorizeUrl(string redirectUrl, string state, OAuthScope scope, string responseType = "code")
 {
     return(OAuthApi.GetAuthorizeUrl(WechatAppConfig.AppId, redirectUrl, state, scope, responseType));
 }
Beispiel #35
0
 public string BuildOAuthUrl(string redirectUrl, OAuthScope scope, string state)
 {
     return String.Format(s_weixin_oauth_format_url,
         AppID, redirectUrl, scope.ToString().ToLower(), state);
 }
Beispiel #36
0
 public PayOAuthAttribute(string appId, string oauthCallbackUrl, OAuthScope oauthScope = OAuthScope.snsapi_userinfo)
     : base(appId, oauthCallbackUrl, oauthScope)
 {
     base._appId = base._appId ?? System.Configuration.ConfigurationManager.AppSettings["TenPayV3_AppId"];
 }
Beispiel #37
0
        //static string appID = "wxa0a406d80dfc308f";
        //static string appSercet = "81e553a85171409db202c70785aed59f";
        /// <summary>
        /// 获取用户信息,如果没有尝试过获取授权会自动获取授权。
        /// 该方法会自动使用微云端进行授权操作。
        /// <para>如果没有尝试获取过获取授权,该方法只对非AJAX GET请求有效</para>
        /// </summary> 
        /// <param name="scope"></param> 
        /// <returns></returns>
        public static WeiXinUserInfo GetUserInfoWithAutoAuth(OAuthScope scope = OAuthScope.snsapi_base)
        {
            string key = WEIXIN_USERINFO;
            HttpContext context = HttpContext.Current;
            WeiXinUserInfo userinfo = HttpContext.Current.Session[key] as WeiXinUserInfo;
            string requestUrl = context.Request.Url.AbsoluteUri;

            //如果当前请求为Get请求并且为非Ajax请求
            if (context.Request.HttpMethod.ToUpper() == "GET" &&
                   context.Request.Headers["X-Requested-With"] != "XMLHttpRequest")
            {

                if ((userinfo == null) || (userinfo.UserInfo == null && scope == OAuthScope.snsapi_userinfo))
                {
                    //如果扩展信息为空或者appid,appsercet为空,或者未启用高级直接返回。
                    if (string.IsNullOrEmpty(_oAuthAppID) ||
                        string.IsNullOrEmpty(_oAuthAppSercet)
                        )
                    {
                        userinfo = new WeiXinUserInfo(false, null, null);
                    }
                    else
                    {
                        Log.Default.Debug("wx ouath session为空重新授权,url:" + requestUrl + ";");
                        string backUrl = string.Format("{1}/dooauth.aspx?callBack={0}", context.Server.UrlEncode(context.Request.Url.AbsoluteUri), ConfigurationManager.AppSettings["ClientDeployDomain"]);
                        string url = OAuth.GetAuthorizeUrl(_oAuthAppID, backUrl, "STATE", scope);
                        HttpContext.Current.Response.Redirect(url);
                    }

                }
            }
            return userinfo;
        }
Beispiel #38
0
        /*此接口不提供异步方法*/
        /// <summary>
        /// 获取验证地址
        /// </summary>
        /// <param name="appId">公众号的唯一标识</param>
        /// <param name="redirectUrl">授权后重定向的回调链接地址,请使用urlencode对链接进行处理</param>
        /// <param name="state">重定向后会带上state参数,开发者可以填写a-zA-Z0-9的参数值,最多128字节</param>
        /// <param name="scope">应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)</param>
        /// <param name="responseType">返回类型,请填写code(或保留默认)</param>
        /// <param name="addConnectRedirect">加上后可以解决40029-invalid code的问题(测试中)</param>
        /// <returns></returns>
        public static string GetAuthorizeUrl(string appId, string redirectUrl, string state, OAuthScope scope, string responseType = "code", bool addConnectRedirect = true)
        {
            var url =
                string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type={2}&scope={3}&state={4}{5}#wechat_redirect",
                              appId.AsUrlData(), redirectUrl.AsUrlData(), responseType.AsUrlData(), scope.ToString("g").AsUrlData(), state.AsUrlData(),
                              addConnectRedirect ? "&connect_redirect=1" : "");

            /* 这一步发送之后,客户会得到授权页面,无论同意或拒绝,都会返回redirectUrl页面。
             * 如果用户同意授权,页面将跳转至 redirect_uri/?code=CODE&state=STATE。这里的code用于换取access_token(和通用接口的access_token不通用)
             * 若用户禁止授权,则重定向后不会带上code参数,仅会带上state参数redirect_uri?state=STATE
             */
            return(url);
        }
Beispiel #39
0
        /// <summary>
        /// 获取显性授权url
        /// 回调后微信传入两个参数 code,state 带用户信息
        /// </summary>
        /// <param name="redirectUrl"></param>
        /// <param name="parm">接收参数为state</param>
        /// <param name="scope">应用授权作用域,snsapi_base (不弹出授权页面,直接跳转,只能获取用户openid),snsapi_userinfo (弹出授权页面,可通过openid拿到昵称、性别、所在地。并且,即使在未关注的情况下,只要用户授权,也能获取其信息)</param>
        /// <returns></returns>
        public static string OauthUrl(string redirectUrl, string parm, OAuthScope scope)
        {
            string url = OAuthApi.GetAuthorizeUrl(AppId, redirectUrl, parm, scope);

            return(url);
        }
Beispiel #40
0
 public CustomSenparcOAuthAttribute(string appId, string oauthCallbackUrl, OAuthScope oauthScope = OAuthScope.snsapi_userinfo)
     : base(appId, oauthCallbackUrl, oauthScope)
 {
     base._appId = base._appId ?? Service.Config.AppId;
 }
 public CustomOAuthAttribute(string appid, string oauthCallbackUrl, OAuthScope oauthScope = OAuthScope.snsapi_userinfo) : base(appid, oauthCallbackUrl, oauthScope)
 {
     _appId ??= Config.SenparcWeixinSetting.WeixinAppId;
     //_appId = Config.SenparcWeixinSetting.WeixinAppId;  // 如果微信的注册在app.UseMvc下面注册将会回 取不到
 }
Beispiel #42
0
 /// <summary>
 /// 获取OAuth授权的Url地址。
 /// </summary>
 /// <param name="url">需要跳转的目标地址。</param>
 /// <param name="scope">OAuth域。</param>
 /// <param name="state">状态参数。</param>
 /// <returns>绝对的Url地址。</returns>
 public string GetAuthorizeUrl(string url, OAuthScope scope, string state = null)
 {
     var appId = _accountModel.AppId;
     var redirectUrl = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect", appId, url, "snsapi_" + scope.ToString().ToLower(), state);
     return redirectUrl;
 }
        /// <summary>
        /// Get URL to use for redirection at SHOPIFY OAUTH 2.0 authorization server, asking for permission to access intended store.
        /// </summary>
        /// <param name="shopName">Authorization shop name (w/o '.myshopify.com', only shop name). In case it contains '.myshopify.com' then it would be trimmed out to continue</param>
        /// <param name="scope">SHOPIFY OAUTH 2.0 permission scope(s) for which store admin  will be asked permission for.</param>
        /// <returns>Returns instance of URL that can be used to redirect your current request to initiate SHOPIFY authentication / authorization process.</returns>
        /// <exception cref="ArgumentNullException">Throws argument null exception if input parameters are null or empty.</exception>
        public string GetOAuthUrl(string shopName, OAuthScope scope)
        {
            if (string.IsNullOrEmpty(shopName))
            {
                throw new ArgumentNullException("shopName");
            }

            if (shopName.EndsWith(AppResources.MyShopifyDomain, StringComparison.InvariantCulture))
            {
                var indexOfShopifyDomain = shopName.IndexOf(AppResources.MyShopifyDomain, StringComparison.InvariantCulture);
                shopName = shopName.Substring(0, indexOfShopifyDomain);
            }

            return string.Format(
                CultureInfo.InvariantCulture,
                AppResources.AuthorizationUrl,
                shopName,
                this.Configuration.ApiKey,
                ScopeBuilder.Build(scope));
        }