Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = AuthorizeOptions.ISSUER,

                    ValidateAudience = true,

                    ValidAudience    = AuthorizeOptions.AUDIENCE,
                    ValidateLifetime = true,

                    IssuerSigningKey         = AuthorizeOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                };
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSwaggerGen(c =>
            {
                c.OperationFilter <MyHeaderFilter>();

                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "Test API",
                    Description = "ASP.NET Core Web API"
                });
            });
            services.AddSwaggerDocumentation();
        }
Пример #2
0
        public async Task <IActionResult> Authorize(
            [FromBody] AuthorizeOptions options)
        {
            var card = await _card.AuthorizeAsync(options);

            return(Json(card));
        }
Пример #3
0
        private static async Task <SessionAuthorizationTransaction> GenerateTransaction(
            IJSRuntime jsRuntime,
            AuthorizeOptions authorizeOptions,
            bool responseTypeIncludesIdToken)
        {
            string lastUsedConnection = string.IsNullOrEmpty(authorizeOptions.Realm) ? authorizeOptions.Connection : authorizeOptions.Realm;

            string appState = string.IsNullOrEmpty(authorizeOptions.AppState) ? CommonAuthentication.GenerateNonce(authorizeOptions.KeyLength) : authorizeOptions.AppState;

            authorizeOptions.State = string.IsNullOrEmpty(authorizeOptions.State) ? CommonAuthentication.GenerateNonce(authorizeOptions.KeyLength) : authorizeOptions.State;
            string nonce = responseTypeIncludesIdToken ? string.IsNullOrEmpty(authorizeOptions.Nonce) ? CommonAuthentication.GenerateNonce(authorizeOptions.KeyLength) : authorizeOptions.Nonce : null;

            SessionAuthorizationTransaction transaction = new SessionAuthorizationTransaction()
            {
                Nonce        = nonce,
                AppState     = appState,
                State        = authorizeOptions.State,
                CodeVerifier = authorizeOptions.CodeVerifier,
                RedirectUri  = authorizeOptions.RedirectUri,
                Connnection  = lastUsedConnection,
            };

            await Storage.SetItem(
                jsRuntime,
                $"{authorizeOptions.Namespace}{authorizeOptions.State}",
                transaction
                ).ConfigureAwait(false);

            return(transaction);
        }
Пример #4
0
        /// <summary>
        /// Process a new Authentication trasanction.
        /// </summary>
        /// <param name="jsRuntime">The <see cref="IJSRuntime"/> instance.</param>
        /// <param name="authorizeOptions">The <see cref="AuthorizeOptions"/> instance.</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
        internal static async Task <AuthorizeOptions> Proccess(IJSRuntime jsRuntime, AuthorizeOptions authorizeOptions)
        {
            if (authorizeOptions is null)
            {
                throw new ArgumentNullException(nameof(authorizeOptions));
            }

            Utils.ValidateObject(authorizeOptions);

            bool responseTypeIncludesIdToken = authorizeOptions.ResponseType == ResponseTypes.IdToken || authorizeOptions.ResponseType == ResponseTypes.TokenAndIdToken;

            SessionAuthorizationTransaction transaction = await GenerateTransaction(
                jsRuntime,
                authorizeOptions,
                responseTypeIncludesIdToken
                ).ConfigureAwait(false);

            if (string.IsNullOrEmpty(authorizeOptions.State))
            {
                authorizeOptions.State = transaction.State;
            }

            if (responseTypeIncludesIdToken && string.IsNullOrEmpty(authorizeOptions.Nonce))
            {
                authorizeOptions.Nonce = transaction.Nonce;
            }

            return(authorizeOptions);
        }
        public ActionResult Token()
        {
            var username = Request.Headers["username"];
            var password = Request.Headers["password"];

            var identity = GetIdentity(username, password);

            if (identity == null)
            {
                return(NotFound());
            }

            var now = DateTime.UtcNow;

            var jwt = new JwtSecurityToken(
                issuer: AuthorizeOptions.ISSUER,
                audience: AuthorizeOptions.AUDIENCE,
                notBefore: now,
                claims: identity.Claims,
                expires: now.Add(TimeSpan.FromMinutes(AuthorizeOptions.LIFETIME)),
                signingCredentials: new SigningCredentials(AuthorizeOptions.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256));
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            var response = new
            {
                access_token = encodedJwt,
                username     = identity.Name
            };

            Response.ContentType = "application/json";

            return(Ok(encodedJwt));
        }
Пример #6
0
 public AuthenticateManager(IDataBaseProvider dataBaseProvider, IOptions <AuthorizeOptions> options)
 {
     DataBaseProvider = dataBaseProvider;
     Options          = options.Value;
     User             = new UserModel();
     Encryptor        = SHA256.Create();
     Handler          = new JwtSecurityTokenHandler();
 }
Пример #7
0
        /// <summary>
        /// Builds the an authorization URI.
        /// </summary>
        /// <param name="buildAuthorizedUrlOptions">A <see cref="AuthorizeOptions"/> param.</param>
        /// <returns>An <see cref="string"/> representing an authorization URI.</returns>
        public static string BuildAuthorizeUrl(AuthorizeOptions buildAuthorizedUrlOptions)
        {
            if (buildAuthorizedUrlOptions is null)
            {
                throw new ArgumentNullException(nameof(buildAuthorizedUrlOptions));
            }

            Utils.ValidateObject(buildAuthorizedUrlOptions);

            var responseType = CommonAuthentication.ParseResponseType(buildAuthorizedUrlOptions.ResponseType);
            var responseMode = CommonAuthentication.ParseResponseMode(buildAuthorizedUrlOptions.ResponseMode);

            var path  = new PathString("/authorize");
            var query = new QueryString();

            query = query.Add("response_type", responseType);
            query = query.Add("state", buildAuthorizedUrlOptions.State);
            query = query.Add("nonce", buildAuthorizedUrlOptions.Nonce);
            query = query.Add("client_id", buildAuthorizedUrlOptions.ClientID);
            query = query.Add("scope", buildAuthorizedUrlOptions.Scope);

            if (buildAuthorizedUrlOptions.CodeChallengeMethod != CodeChallengeMethods.None)
            {
                string codechallengeMethod = CommonAuthentication.ParseCodeChallengeMethod(buildAuthorizedUrlOptions.CodeChallengeMethod);

                query = query.Add("code_challenge_method", codechallengeMethod);
                query = query.Add("code_challenge", buildAuthorizedUrlOptions.CodeChallenge);
            }

            if (!string.IsNullOrEmpty(buildAuthorizedUrlOptions.Connection))
            {
                query = query.Add("connection", buildAuthorizedUrlOptions.Connection);
            }

            if (!string.IsNullOrEmpty(buildAuthorizedUrlOptions.Audience))
            {
                query = query.Add("audience", buildAuthorizedUrlOptions.Audience);
            }

            if (!string.IsNullOrEmpty(responseMode))
            {
                query = query.Add("response_mode", responseMode);
            }

            query = query.Add("redirect_uri", buildAuthorizedUrlOptions.RedirectUri);

            UriBuilder uriBuilder = new UriBuilder
            {
                Scheme = "https",
                Host   = buildAuthorizedUrlOptions.Domain,
                Path   = path,
                Query  = query.ToUriComponent(),
            };

            return(uriBuilder.Uri.AbsoluteUri);
        }
Пример #8
0
        private static bool RunAuthorize(AuthorizeOptions opts)
        {
            var deviceManager         = new DeviceManager(Storage, ApiClient);
            var authorizationResponse = deviceManager.Authorize();

            Console.WriteLine("Open the browser and navigate to: {0}?user_code={1}" +
                              "\nWhen asked for the code, enter: {1}", authorizationResponse.verification_url, authorizationResponse.user_code);

            return(true);
        }
Пример #9
0
        private static bool RunAuthorize(AuthorizeOptions opts)
        {
            var deviceManager = new DeviceManager(Storage, ApiClient);
            var authorizationResponse = deviceManager.Authorize();

            Console.WriteLine("Open the browser and navigate to: {0}?user_code={1}" +
                              "\nWhen asked for the code, enter: {1}", authorizationResponse.verification_url, authorizationResponse.user_code);

            return true;
        }
Пример #10
0
        public static void OnReady()
        {
            //object provider;
            //provider =  Ext.create("Att.Provider");
            // provider.As<Provider>().authorizeApp(new AuthorizeOptions {
            //       authScope = "TL,MOBO,MIM,DC",
            //        //TODO: apiBasePath:        "att"
            // },

            AuthorizeOptions config = new AuthorizeOptions
            {
                authScope = "TL,MOBO,MIM,DC",
                //TODO: apiBasePath:        "att"
            };
        }
Пример #11
0
        public async Task test_full_flow_and_expiration()
        {
            //client.

            var opts = new AuthorizeOptions
            {
                ClientId    = secrets.OAuthClientId,
                RedirectUri = redirectUrl,
                State       = "random",
                Scope       = "wallet:accounts:read"
            };

            var authUrl = OAuthHelper.GetAuthorizeUrl(opts);

            authUrl.Dump();

            ("Execute the following URL and authorize the app. " +
             "Then, copy the callback?code=VALUE value to the secrets file.").Dump();
        }
Пример #12
0
        public async Task can_create_authorization_url()
        {
            var opts = new AuthorizeOptions
            {
                ClientId    = "YOUR_CLIENT_ID",
                RedirectUri = "YOUR_REDIRECT_URL",
                State       = "SECURE_RANDOM",
                Scope       = "wallet:accounts:read"
            };
            var authUrl = OAuthHelper.GetAuthorizeUrl(opts);

            var url =
                "https://www.coinbase.com/oauth/authorize?response_type=code&client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URL&state=SECURE_RANDOM&scope=wallet%3Aaccounts%3Aread";


            var response = await authUrl.GetAsync();

            server.ShouldHaveExactCall(url);
        }
Пример #13
0
        /// <summary>
        /// When redirecting a user to Coinbase to authorize access to your application,
        /// you’ll need to construct the authorization URL with the correct parameters
        /// and scopes. Here’s a list of parameters you should always specify:
        /// </summary>
        public static string GetAuthorizeUrl(AuthorizeOptions opts)
        {
            var url = AuthorizeEndpoint
                      .SetQueryParam("response_type", "code")
                      .SetQueryParam("client_id", opts.ClientId)
                      .SetQueryParam("redirect_uri", opts.RedirectUri)
                      .SetQueryParam("state", opts.State)
                      .SetQueryParam("scope", opts.Scope)
                      .SetQueryParam("layout", opts.Layout)
                      .SetQueryParam("referral", opts.Referral)
                      .SetQueryParam("account", opts.Account);

            foreach (var kv in opts.Meta)
            {
                url.SetQueryParam($"meta[{kv.Key}]", kv.Value);
            }

            return(url);
        }
Пример #14
0
        /// <summary>
        /// 授权验证
        /// </summary>
        /// <param name="request">认证授权信息</param>
        /// <returns></returns>
        public static AuthorizeResult CheckAuthorization(AuthorizeOptions request)
        {
            if (request == null)
            {
                return(AuthorizeResult.ForbidResult());
            }
            var operation = new OperationDto()
            {
                ActionCode     = request.Action,
                ControllerCode = request.Controller
            };
            var user = AuthenticationUser <long> .GetUserFromClaims(request.Claims?.Select(c => new Claim(c.Key, c.Value)).ToList());

            var allowAccess = CheckAuthorization(user, operation);

            return(new AuthorizeResult()
            {
                Status = allowAccess ? AuthorizationStatus.Success : AuthorizationStatus.Forbid
            });
        }
Пример #15
0
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();

            var https        = new HttpsOptions();
            var blog         = new BlogOptions();
            var notification = new NotificationOptions();
            var swagger      = new SwaggerOptions();
            var storage      = new StorageOptions();
            var cors         = new CorsOptions();
            var jwt          = new JwtOptions();
            var worker       = new WorkerOptions();
            var tencentCloud = new TencentCloudOptions();
            var authorize    = new AuthorizeOptions();

            PreConfigure <HttpsOptions>(options =>
            {
                var httpsOption = configuration.GetSection("https");
                Configure <HttpsOptions>(httpsOption);

                options.ListenAddress   = httpsOption.GetValue <string>(nameof(options.ListenAddress));
                options.ListenPort      = httpsOption.GetValue <int>(nameof(options.ListenPort));
                options.PublicCertFile  = httpsOption.GetValue <string>(nameof(options.PublicCertFile));
                options.PrivateCertFile = httpsOption.GetValue <string>(nameof(options.PrivateCertFile));

                https = options;
            });

            PreConfigure <BlogOptions>(options =>
            {
                var blogOption = configuration.GetSection("blog");
                Configure <BlogOptions>(blogOption);

                options.StaticUrl = blogOption.GetValue <string>(nameof(options.StaticUrl));
                options.ApiUrl    = blogOption.GetValue <string>(nameof(options.ApiUrl));
                options.WebUrl    = blogOption.GetValue <string>(nameof(options.WebUrl));
                options.AdminUrl  = blogOption.GetValue <string>(nameof(options.AdminUrl));

                blog = options;
            });

            PreConfigure <NotificationOptions>(options =>
            {
                var notificationOption = configuration.GetSection("notification");
                Configure <NotificationOptions>(notificationOption);

                options.FtqqUrl = notificationOption.GetValue <string>(nameof(options.FtqqUrl));

                notification = options;
            });

            PreConfigure <SwaggerOptions>(options =>
            {
                var swaggerOption = configuration.GetSection("swagger");
                Configure <SwaggerOptions>(swaggerOption);

                options.Version       = swaggerOption.GetValue <string>(nameof(options.Version));
                options.Name          = swaggerOption.GetValue <string>(nameof(options.Name));
                options.Title         = swaggerOption.GetValue <string>(nameof(options.Title));
                options.Description   = swaggerOption.GetValue <string>(nameof(options.Description));
                options.RoutePrefix   = swaggerOption.GetValue <string>(nameof(options.RoutePrefix));
                options.DocumentTitle = swaggerOption.GetValue <string>(nameof(options.DocumentTitle));

                swagger = options;
            });
            PreConfigure <StorageOptions>(options =>
            {
                var storageOption = configuration.GetSection("storage");
                Configure <StorageOptions>(storageOption);

                options.Mongodb        = storageOption.GetValue <string>(nameof(options.Mongodb));
                options.RedisIsEnabled = storageOption.GetValue <bool>(nameof(options.RedisIsEnabled));
                options.Redis          = storageOption.GetValue <string>(nameof(options.Redis));

                storage = options;
            });
            PreConfigure <CorsOptions>(options =>
            {
                var corsOption = configuration.GetSection("cors");
                Configure <CorsOptions>(corsOption);

                options.PolicyName = corsOption.GetValue <string>(nameof(options.PolicyName));
                options.Origins    = corsOption.GetValue <string>(nameof(options.Origins));

                cors = options;
            });
            PreConfigure <JwtOptions>(options =>
            {
                var jwtOption = configuration.GetSection("jwt");
                Configure <JwtOptions>(jwtOption);

                options.Issuer     = jwtOption.GetValue <string>(nameof(options.Issuer));
                options.Audience   = jwtOption.GetValue <string>(nameof(options.Audience));
                options.SigningKey = jwtOption.GetValue <string>(nameof(options.SigningKey));

                jwt = options;
            });
            PreConfigure <WorkerOptions>(options =>
            {
                var workerOption = configuration.GetSection("worker");
                Configure <WorkerOptions>(workerOption);

                options.IsEnabled = workerOption.GetValue <bool>(nameof(options.IsEnabled));
                options.Cron      = workerOption.GetValue <string>(nameof(options.Cron));

                worker = options;
            });
            PreConfigure <TencentCloudOptions>(options =>
            {
                var tencentCloudOption = configuration.GetSection("tencentCloud");
                Configure <TencentCloudOptions>(tencentCloudOption);

                options.SecretId  = tencentCloudOption.GetValue <string>(nameof(options.SecretId));
                options.SecretKey = tencentCloudOption.GetValue <string>(nameof(options.SecretKey));

                tencentCloud = options;
            });
            PreConfigure <AuthorizeOptions>(options =>
            {
                var authorizeOption = configuration.GetSection("authorize");
                var githubOption    = authorizeOption.GetSection("github");
                var giteeOption     = authorizeOption.GetSection("gitee");
                var alipayOption    = authorizeOption.GetSection("alipay");
                var dingtalkOption  = authorizeOption.GetSection("dingtalk");
                var microsoftOption = authorizeOption.GetSection("microsoft");
                var weiboOptions    = authorizeOption.GetSection("weibo");
                var qqOptions       = authorizeOption.GetSection("qq");

                Configure <AuthorizeOptions>(authorizeOption);
                Configure <GithubOptions>(githubOption);
                Configure <GiteeOptions>(giteeOption);
                Configure <AlipayOptions>(alipayOption);
                Configure <DingtalkOptions>(dingtalkOption);
                Configure <MicrosoftOptions>(microsoftOption);
                Configure <WeiboOptions>(weiboOptions);
                Configure <QQOptions>(qqOptions);

                options.Github = new GithubOptions
                {
                    ClientId     = githubOption.GetValue <string>(nameof(options.Github.ClientId)),
                    ClientSecret = githubOption.GetValue <string>(nameof(options.Github.ClientSecret)),
                    RedirectUrl  = githubOption.GetValue <string>(nameof(options.Github.RedirectUrl)),
                    Scope        = githubOption.GetValue <string>(nameof(options.Github.Scope))
                };
                options.Gitee = new GiteeOptions
                {
                    ClientId     = giteeOption.GetValue <string>(nameof(options.Gitee.ClientId)),
                    ClientSecret = giteeOption.GetValue <string>(nameof(options.Gitee.ClientSecret)),
                    RedirectUrl  = giteeOption.GetValue <string>(nameof(options.Gitee.RedirectUrl)),
                    Scope        = giteeOption.GetValue <string>(nameof(options.Gitee.Scope))
                };
                options.Alipay = new AlipayOptions
                {
                    AppId       = alipayOption.GetValue <string>(nameof(options.Alipay.AppId)),
                    RedirectUrl = alipayOption.GetValue <string>(nameof(options.Alipay.RedirectUrl)),
                    Scope       = alipayOption.GetValue <string>(nameof(options.Alipay.Scope)),
                    PrivateKey  = alipayOption.GetValue <string>(nameof(options.Alipay.PrivateKey)),
                    PublicKey   = alipayOption.GetValue <string>(nameof(options.Alipay.PublicKey))
                };
                options.Dingtalk = new DingtalkOptions
                {
                    AppId       = dingtalkOption.GetValue <string>(nameof(options.Dingtalk.AppId)),
                    AppSecret   = dingtalkOption.GetValue <string>(nameof(options.Dingtalk.AppSecret)),
                    RedirectUrl = dingtalkOption.GetValue <string>(nameof(options.Dingtalk.RedirectUrl)),
                    Scope       = dingtalkOption.GetValue <string>(nameof(options.Dingtalk.Scope))
                };
                options.Microsoft = new MicrosoftOptions
                {
                    ClientId     = microsoftOption.GetValue <string>(nameof(options.Microsoft.ClientId)),
                    ClientSecret = microsoftOption.GetValue <string>(nameof(options.Microsoft.ClientSecret)),
                    RedirectUrl  = microsoftOption.GetValue <string>(nameof(options.Microsoft.RedirectUrl)),
                    Scope        = microsoftOption.GetValue <string>(nameof(options.Microsoft.Scope))
                };
                options.Weibo = new WeiboOptions
                {
                    ClientId     = weiboOptions.GetValue <string>(nameof(options.Weibo.ClientId)),
                    ClientSecret = weiboOptions.GetValue <string>(nameof(options.Weibo.ClientSecret)),
                    RedirectUrl  = weiboOptions.GetValue <string>(nameof(options.Weibo.RedirectUrl)),
                    Scope        = weiboOptions.GetValue <string>(nameof(options.Weibo.Scope))
                };
                options.QQ = new QQOptions
                {
                    ClientId     = qqOptions.GetValue <string>(nameof(options.QQ.ClientId)),
                    ClientSecret = qqOptions.GetValue <string>(nameof(options.QQ.ClientSecret)),
                    RedirectUrl  = qqOptions.GetValue <string>(nameof(options.QQ.RedirectUrl)),
                    Scope        = qqOptions.GetValue <string>(nameof(options.QQ.Scope))
                };

                authorize = options;
            });
            PreConfigure <AppOptions>(options =>
            {
                options.Https        = https;
                options.Blog         = blog;
                options.Swagger      = swagger;
                options.Storage      = storage;
                options.Cors         = cors;
                options.Jwt          = jwt;
                options.Worker       = worker;
                options.TencentCloud = tencentCloud;
                options.Authorize    = authorize;

                Configure <AppOptions>(item =>
                {
                    item.Swagger      = swagger;
                    item.Storage      = storage;
                    item.Cors         = cors;
                    item.Jwt          = jwt;
                    item.Worker       = worker;
                    item.TencentCloud = tencentCloud;
                    item.Authorize    = authorize;
                });
            });
        }
Пример #16
0
        public CloudyAdminConfigurator Authorize(AuthorizeOptions authorizeOptions)
        {
            Options.AuthorizeOptions = authorizeOptions;

            return this;
        }
Пример #17
0
        public override void PreConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();

            var swagger      = new SwaggerOptions();
            var storage      = new StorageOptions();
            var cors         = new CorsOptions();
            var jwt          = new JwtOptions();
            var worker       = new WorkerOptions();
            var signature    = new SignatureOptions();
            var tencentCloud = new TencentCloudOptions();
            var authorize    = new AuthorizeOptions();
            var ftqq         = new FtqqOptions();

            PreConfigure <SwaggerOptions>(options =>
            {
                var swaggerOption = configuration.GetSection("swagger");
                Configure <SwaggerOptions>(swaggerOption);

                options.Version       = swaggerOption.GetValue <string>(nameof(options.Version));
                options.Name          = swaggerOption.GetValue <string>(nameof(options.Name));
                options.Title         = swaggerOption.GetValue <string>(nameof(options.Title));
                options.Description   = swaggerOption.GetValue <string>(nameof(options.Description));
                options.RoutePrefix   = swaggerOption.GetValue <string>(nameof(options.RoutePrefix));
                options.DocumentTitle = swaggerOption.GetValue <string>(nameof(options.DocumentTitle));

                swagger = options;
            });
            PreConfigure <StorageOptions>(options =>
            {
                var storageOption = configuration.GetSection("storage");
                Configure <StorageOptions>(storageOption);

                options.EnableDb         = storageOption.GetValue <string>(nameof(options.EnableDb));
                options.ConnectionString = storageOption.GetValue <string>(options.EnableDb);
                options.RedisStatus      = storageOption.GetValue <bool>(nameof(options.RedisStatus));
                options.RedisConnection  = storageOption.GetValue <string>(nameof(options.RedisConnection));

                storage = options;
            });
            PreConfigure <CorsOptions>(options =>
            {
                var corsOption = configuration.GetSection("cors");
                Configure <CorsOptions>(corsOption);

                options.PolicyName = corsOption.GetValue <string>(nameof(options.PolicyName));
                options.Origins    = corsOption.GetValue <string>(nameof(options.Origins));

                cors = options;
            });
            PreConfigure <JwtOptions>(options =>
            {
                var jwtOption = configuration.GetSection("jwt");
                Configure <JwtOptions>(jwtOption);

                options.Issuer     = jwtOption.GetValue <string>(nameof(options.Issuer));
                options.Audience   = jwtOption.GetValue <string>(nameof(options.Audience));
                options.SigningKey = jwtOption.GetValue <string>(nameof(options.SigningKey));

                jwt = options;
            });
            PreConfigure <WorkerOptions>(options =>
            {
                var workerOption = configuration.GetSection("worker");
                Configure <WorkerOptions>(workerOption);

                options.IsEnabled = workerOption.GetValue <bool>(nameof(options.IsEnabled));
                options.Cron      = workerOption.GetValue <string>(nameof(options.Cron));

                worker = options;
            });
            //PreConfigure<TencentCloudOptions>(options =>
            //{
            //    var tencentCloudOption = configuration.GetSection("tencentCloud");
            //    Configure<TencentCloudOptions>(tencentCloudOption);

            //    options.SecretId = tencentCloudOption.GetValue<string>(nameof(options.SecretId));
            //    options.SecretKey = tencentCloudOption.GetValue<string>(nameof(options.SecretKey));

            //    tencentCloud = options;
            //});
            PreConfigure <SignatureOptions>(options =>
            {
                var signatureOption = configuration.GetSection("signature");

                options.Path = signatureOption.GetValue <string>(nameof(options.Path));

                foreach (var item in signatureOption.GetSection(nameof(options.Urls)).GetChildren())
                {
                    options.Urls.Add(item.GetValue <string>("url"), item.GetValue <string>("param"));
                }

                signature = options;
                Configure <SignatureOptions>(item =>
                {
                    item.Path = signature.Path;
                    item.Urls = signature.Urls;
                });
            });
            PreConfigure <AuthorizeOptions>(options =>
            {
                var authorizeOption = configuration.GetSection("authorize");
                var githubOption    = authorizeOption.GetSection("github");
                var giteeOption     = authorizeOption.GetSection("gitee");
                var alipayOption    = authorizeOption.GetSection("alipay");
                var dingtalkOption  = authorizeOption.GetSection("dingtalk");
                var microsoftOption = authorizeOption.GetSection("microsoft");
                var weiboOptions    = authorizeOption.GetSection("weibo");
                var qqOptions       = authorizeOption.GetSection("qq");

                Configure <AuthorizeOptions>(authorizeOption);
                Configure <GithubOptions>(githubOption);
                //Configure<GiteeOptions>(giteeOption);
                //Configure<AlipayOptions>(alipayOption);
                //Configure<DingtalkOptions>(dingtalkOption);
                //Configure<MicrosoftOptions>(microsoftOption);
                //Configure<WeiboOptions>(weiboOptions);
                //Configure<QQOptions>(qqOptions);

                options.Github = new GithubOptions
                {
                    ClientId     = githubOption.GetValue <string>(nameof(options.Github.ClientId)),
                    ClientSecret = githubOption.GetValue <string>(nameof(options.Github.ClientSecret)),
                    RedirectUrl  = githubOption.GetValue <string>(nameof(options.Github.RedirectUrl)),
                    Scope        = githubOption.GetValue <string>(nameof(options.Github.Scope))
                };
                //options.Gitee = new GiteeOptions
                //{
                //    ClientId = giteeOption.GetValue<string>(nameof(options.Gitee.ClientId)),
                //    ClientSecret = giteeOption.GetValue<string>(nameof(options.Gitee.ClientSecret)),
                //    RedirectUrl = giteeOption.GetValue<string>(nameof(options.Gitee.RedirectUrl)),
                //    Scope = giteeOption.GetValue<string>(nameof(options.Gitee.Scope))
                //};
                //options.Alipay = new AlipayOptions
                //{
                //    AppId = alipayOption.GetValue<string>(nameof(options.Alipay.AppId)),
                //    RedirectUrl = alipayOption.GetValue<string>(nameof(options.Alipay.RedirectUrl)),
                //    Scope = alipayOption.GetValue<string>(nameof(options.Alipay.Scope)),
                //    PrivateKey = alipayOption.GetValue<string>(nameof(options.Alipay.PrivateKey)),
                //    PublicKey = alipayOption.GetValue<string>(nameof(options.Alipay.PublicKey))
                //};
                //options.Dingtalk = new DingtalkOptions
                //{
                //    AppId = dingtalkOption.GetValue<string>(nameof(options.Dingtalk.AppId)),
                //    AppSecret = dingtalkOption.GetValue<string>(nameof(options.Dingtalk.AppSecret)),
                //    RedirectUrl = dingtalkOption.GetValue<string>(nameof(options.Dingtalk.RedirectUrl)),
                //    Scope = dingtalkOption.GetValue<string>(nameof(options.Dingtalk.Scope))
                //};
                //options.Microsoft = new MicrosoftOptions
                //{
                //    ClientId = microsoftOption.GetValue<string>(nameof(options.Microsoft.ClientId)),
                //    ClientSecret = microsoftOption.GetValue<string>(nameof(options.Microsoft.ClientSecret)),
                //    RedirectUrl = microsoftOption.GetValue<string>(nameof(options.Microsoft.RedirectUrl)),
                //    Scope = microsoftOption.GetValue<string>(nameof(options.Microsoft.Scope))
                //};
                //options.Weibo = new WeiboOptions
                //{
                //    ClientId = weiboOptions.GetValue<string>(nameof(options.Weibo.ClientId)),
                //    ClientSecret = weiboOptions.GetValue<string>(nameof(options.Weibo.ClientSecret)),
                //    RedirectUrl = weiboOptions.GetValue<string>(nameof(options.Weibo.RedirectUrl)),
                //    Scope = weiboOptions.GetValue<string>(nameof(options.Weibo.Scope))
                //};
                //options.QQ = new QQOptions
                //{
                //    ClientId = qqOptions.GetValue<string>(nameof(options.QQ.ClientId)),
                //    ClientSecret = qqOptions.GetValue<string>(nameof(options.QQ.ClientSecret)),
                //    RedirectUrl = qqOptions.GetValue<string>(nameof(options.QQ.RedirectUrl)),
                //    Scope = qqOptions.GetValue<string>(nameof(options.QQ.Scope))
                //};
                authorize = options;
            });
            PreConfigure <FtqqOptions>(options =>
            {
                var ftqqOptions = configuration.GetSection("ftqq");
                Configure <FtqqOptions>(ftqqOptions);

                options.ApiUrl = ftqqOptions.GetValue <string>(nameof(options.ApiUrl));
                options.Token  = ftqqOptions.GetValue <string>(nameof(options.Token));

                ftqq = options;
            });

            PreConfigure <AppOptions>(options =>
            {
                options.Swagger      = swagger;
                options.Storage      = storage;
                options.Cors         = cors;
                options.Jwt          = jwt;
                options.Worker       = worker;
                options.Signature    = signature;
                options.TencentCloud = tencentCloud;
                options.Authorize    = authorize;
                options.Ftqq         = ftqq;

                Configure <AppOptions>(item =>
                {
                    item.Swagger      = swagger;
                    item.Storage      = storage;
                    item.Cors         = cors;
                    item.Jwt          = jwt;
                    item.Worker       = worker;
                    item.Signature    = signature;
                    item.TencentCloud = tencentCloud;
                    item.Authorize    = authorize;
                    item.Ftqq         = ftqq;
                });
            });
        }
Пример #18
0
 public AuthorizeMiddleware(RequestDelegate next, AuthorizeOptions options)
 {
     _next    = next;
     _options = options;
 }
Пример #19
0
 /// <summary>
 /// Initiates the Authorization flow by calling the IDP's /authorize enpoint.
 /// </summary>
 /// <param name="jsRuntime">A <see cref="IJSRuntime"/> param.</param>
 /// <param name="navigationManager">A <see cref="NavigationManager"/> param.</param>
 /// <param name="authorizeOptions">A <see cref="AuthorizeOptions"/> param.</param>
 /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
 public static async Task Authorize(IJSRuntime jsRuntime, NavigationManager navigationManager, AuthorizeOptions authorizeOptions)
 {
     await Authorize(jsRuntime, null, navigationManager, authorizeOptions).ConfigureAwait(false);
 }
Пример #20
0
 /// <summary>
 /// Initiates the Authorization flow by calling the IDP's /authorize enpoint inside a popup window.
 /// </summary>
 /// <param name="jsRuntime">A <see cref="IJSRuntime"/> param.</param>
 /// <param name="objectReference">A <see cref="DotNetObjectReference"/> param.</param>
 /// <param name="navigationManager">A <see cref="NavigationManager"/> param.</param>
 /// <param name="authorizeOptions">A <see cref="AuthorizeOptions"/> param.</param>
 /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
 public static async Task AuthorizePopup(IJSRuntime jsRuntime, object objectReference, NavigationManager navigationManager, AuthorizeOptions authorizeOptions)
 {
     await Authorize(jsRuntime, objectReference, navigationManager, authorizeOptions).ConfigureAwait(false);
 }
Пример #21
0
        /// <summary>
        /// Initiates the Authorization flow by calling the IDP's /authorize endpoint, if an objectReference is passed as param a popup login will be triggered.
        /// </summary>
        /// <param name="jsRuntime">A <see cref="IJSRuntime"/> param.</param>
        /// <param name="objectReference">A <see cref="DotNetObjectReference"/> param.</param>
        /// <param name="navigationManager">A <see cref="NavigationManager"/> param.</param>
        /// <param name="authorizeOptions">A <see cref="AuthorizeOptions"/> param.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        internal static async Task Authorize(IJSRuntime jsRuntime, object objectReference, NavigationManager navigationManager, AuthorizeOptions authorizeOptions)
        {
            if (jsRuntime is null)
            {
                throw new ArgumentNullException(nameof(jsRuntime));
            }

            if (navigationManager is null)
            {
                throw new ArgumentNullException(nameof(navigationManager));
            }

            if (authorizeOptions is null)
            {
                throw new ArgumentNullException(nameof(authorizeOptions));
            }

            Utils.ValidateObject(authorizeOptions);

            authorizeOptions = await TransactionManager.Proccess(jsRuntime, authorizeOptions).ConfigureAwait(false);

            string authorizeUrl = BuildAuthorizeUrl(authorizeOptions);

            // If an objectReference is passed as param a popup login will be triggered.
            if (objectReference == null)
            {
                navigationManager.NavigateTo(authorizeUrl);
            }
            else
            {
                await jsRuntime.InvokeVoidAsync($"{Resources.InteropElementName}.popupLogin", objectReference, authorizeUrl).ConfigureAwait(false);
            }
        }
Пример #22
0
        public async Task <Card> AuthorizeAsync(AuthorizeOptions options)
        {
            if (string.IsNullOrWhiteSpace(options?.CardNumber))
            {
                return(null);
            }

            var intTransactionType = int.Parse(options?.IntTranType.ToString());
            var isDefined          = Enum.IsDefined(typeof(TransactionType), intTransactionType);

            if (!isDefined)
            {
                return(null);
            }

            if (options?.TransactionAmount == null)
            {
                return(null);
            }

            if (options?.TransactionAmount == 0)
            {
                return(null);
            }

            RetrieveCardOptions cardOptions = new RetrieveCardOptions()
            {
                CardNumber = options.CardNumber
            };

            var card = await RetrieveCardAsync(cardOptions);

            if (card != null)
            {
                if ((card.CardLimits) == null || ((card.CardLimits) != null && (card.CardLimits.Count < 2)))
                {
                    if ((options.TransactionAmount <= 1500M) && ((TransactionType)options.IntTranType == TransactionType.CardPresent))
                    {
                        var newLimit = new Limit();
                        newLimit.TranType        = TransactionType.CardPresent;
                        newLimit.LimitDate       = DateTimeOffset.Now.Date;
                        newLimit.TranTypeLimit   = 1500M;
                        newLimit.TranTypeBalance = options.TransactionAmount;
                        card.CardLimits.Add(newLimit);
                        card.CurrentBalance += options.TransactionAmount;
                    }
                    else if ((options.TransactionAmount <= 500M) && ((TransactionType)options.IntTranType == TransactionType.Ecommerce))
                    {
                        var newLimit = new Limit();
                        newLimit.TranType        = TransactionType.Ecommerce;
                        newLimit.LimitDate       = DateTimeOffset.Now.Date;
                        newLimit.TranTypeLimit   = 500M;
                        newLimit.TranTypeBalance = options.TransactionAmount;
                        card.CardLimits.Add(newLimit);
                        card.CurrentBalance += options.TransactionAmount;
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    foreach (var item in card.CardLimits)
                    {
                        if (item.TranType == (TransactionType)intTransactionType)
                        {
                            if (item.LimitDate == DateTimeOffset.Now.Date)
                            {
                                if (item.TranTypeBalance + options.TransactionAmount <= item.TranTypeLimit)
                                {
                                    item.TranTypeBalance = item.TranTypeBalance + options.TransactionAmount;
                                    card.CurrentBalance += options.TransactionAmount;
                                }
                                else
                                {
                                    return(null);
                                }
                            }
                            else
                            {
                                if (options.TransactionAmount <= item.TranTypeLimit)
                                {
                                    item.LimitDate       = DateTimeOffset.Now.Date;
                                    item.TranTypeBalance = options.TransactionAmount;
                                    card.CurrentBalance += options.TransactionAmount;
                                }
                                else
                                {
                                    return(null);
                                }
                            }
                        }
                    }
                }

                _dbContext.Update(card);
                _dbContext.SaveChanges();

                return(card);
            }
            else
            {
                return(null);
            }
        }
Пример #23
0
        /// <summary>
        /// Initiates the Authorization flow by calling the IDP's /authorize enpoint.
        /// </summary>
        /// <param name="jsRuntime">A <see cref="IJSRuntime"/> param.</param>
        /// <param name="navigationManager">A <see cref="NavigationManager"/> param.</param>
        /// <param name="authorizeOptions">A <see cref="AuthorizeOptions"/> param.</param>
        /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns>
        public static async Task Authorize(IJSRuntime jsRuntime, NavigationManager navigationManager, AuthorizeOptions authorizeOptions)
        {
            if (jsRuntime is null)
            {
                throw new ArgumentNullException(nameof(jsRuntime));
            }

            if (navigationManager is null)
            {
                throw new ArgumentNullException(nameof(navigationManager));
            }

            if (authorizeOptions is null)
            {
                throw new ArgumentNullException(nameof(authorizeOptions));
            }

            Utils.ValidateObject(authorizeOptions);

            authorizeOptions = await TransactionManager.Proccess(jsRuntime, authorizeOptions).ConfigureAwait(false);

            string authorizeUrl = BuildAuthorizeUrl(authorizeOptions);

            navigationManager.NavigateTo(authorizeUrl);
        }