当前位置: 首页 > news >正文

颜色选取网站做网站定制的一般什么价位

颜色选取网站,做网站定制的一般什么价位,仿站参考网站,吸引流量的网站在现代 web 应用程序中#xff0c;OAuth 协议是授权和认证的主流选择。为了与多个授权提供商进行无缝对接#xff0c;我们需要一个易于扩展和维护的 OAuth 解决方案。本文将介绍如何构建一个灵活的、支持多提供商的 OAuth 系统#xff0c;包括动态 API 调用、路径参数替换、…        在现代 web 应用程序中OAuth 协议是授权和认证的主流选择。为了与多个授权提供商进行无缝对接我们需要一个易于扩展和维护的 OAuth 解决方案。本文将介绍如何构建一个灵活的、支持多提供商的 OAuth 系统包括动态 API 调用、路径参数替换、查询参数处理等功能。 目录结构 我们将创建一个简单而清晰的目录结构以便于管理我们的代码和配置。以下是本解决方案的整体目录结构 核心模块OAuth.Core ProviderConfiguration 数据模型 在 OAuth.Core 模块我们定义了 ProviderConfiguration 类该类用于配置各个 OAuth 提供商的基本信息和 API 详情。 using System.Collections.Generic; namespace OAuth.Core.Models { /// summary /// 单个 OAuth 提供商的配置 /// /summary public class ProviderConfiguration { public string ProviderName { get; set; } // 提供商名称 public string BaseUrl { get; set; } // 提供商 API 基础路径 public string AuthorizationUrl { get; set; } // 授权 URL public string TokenUrl { get; set; } // 获取 AccessToken URL public string ClientId { get; set; } // 应用的 Client ID public string ClientSecret { get; set; } // 应用的 Client Secret public string RedirectUri { get; set; } // 应用回调的重定向 URL public Liststring Scopes { get; set; } new(); // 授权范围 public Dictionarystring, string CommonHeaders { get; set; } new(); // 公共 Headers public Dictionarystring, ApiConfig Apis { get; set; } new(); // 配置的 API 集合 } /// summary /// 单个 API 的动态配置 /// /summary public class ApiConfig { public string Url { get; set; } // 动态路径 URL例如 /user/{userId} public string Method { get; set; } GET; // HTTP 请求方法 public bool RequiresAuthentication { get; set; } true; // 是否需要 AccessToken public Dictionarystring, string Headers { get; set; } new(); // API 专属 Header 配置 public string BodyFormat { get; set; } application/json; // Body 格式默认 JSON public ListApiParameterConfig Parameters { get; set; } new(); // 参数配置 } /// summary /// API 参数配置 /// /summary public class ApiParameterConfig { public string Name { get; set; } // 参数名称 public string Location { get; set; } // 参数位置path, query, body, header public string DefaultValue { get; set; } // 参数默认值若需要 } } TokenInfo 管理类 TokenInfo 类用于管理和存储 Access Token 和 Refresh Token 的生命周期信息。 using System; namespace OAuth.Core.Models { public class TokenInfo { public string AccessToken { get; set; } public string RefreshToken { get; set; } public DateTime ExpiresAt { get; set; } public bool IsValid DateTime.UtcNow ExpiresAt; } } 结果封装类 Result 通过 ResultT 类封装 API 调用的结果以便于处理成功和失败的状态。 namespace OAuth.Core.Models { public class ResultT { public T Data { get; } public bool IsSuccess { get; } public string Error { get; } private Result(T data, bool isSuccess, string error) { Data data; IsSuccess isSuccess; Error error; } public static ResultT Success(T data) new(data, true, null); public static ResultT Failure(string error) new(default, false, error); } } 核心逻辑实现OAuth.Infrastructure AuthProvider 类 这是实施 OAuth 逻辑的核心类负责发送请求、处理响应以及替换路径参数。 using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Threading.Tasks; using OAuth.Core.Models; namespace OAuth.Infrastructure { public class AuthProvider { private readonly HttpClient _httpClient; private readonly ProviderConfiguration _config; public AuthProvider(HttpClient httpClient, ProviderConfiguration config) { _httpClient httpClient ?? throw new ArgumentNullException(nameof(httpClient)); _config config ?? throw new ArgumentNullException(nameof(config)); } /// summary /// 获取 AccessToken /// /summary public async TaskResultTokenInfo GetAccessTokenAsync(string code) { var url ${_config.BaseUrl}{_config.TokenUrl}; var payload new Dictionarystring, string { { client_id, _config.ClientId }, { client_secret, _config.ClientSecret }, { code, code }, { grant_type, authorization_code }, { redirect_uri, _config.RedirectUri } }; var response await _httpClient.PostAsync(url, new FormUrlEncodedContent(payload)); if (!response.IsSuccessStatusCode) return ResultTokenInfo.Failure(await response.Content.ReadAsStringAsync()); var content await response.Content.ReadAsStringAsync(); var tokenResponse JsonSerializer.DeserializeDictionarystring, object(content); return ResultTokenInfo.Success(new TokenInfo { AccessToken tokenResponse[access_token].ToString(), RefreshToken tokenResponse.ContainsKey(refresh_token) ? tokenResponse[refresh_token].ToString() : null, ExpiresAt DateTime.UtcNow.AddSeconds(Convert.ToDouble(tokenResponse[expires_in])) }); } /// summary /// 执行 API 调用 /// /summary public async TaskResultT CallApiAsyncT(string apiName, Dictionarystring, object parameters null) { if (!_config.Apis.TryGetValue(apiName, out var apiConfig)) return ResultT.Failure($未找到 API {apiName} 的配置); // 动态替换路径参数 var url ReplacePathParameters(${_config.BaseUrl}{apiConfig.Url}, parameters); // 构建 HTTP 请求 var request new HttpRequestMessage(new HttpMethod(apiConfig.Method), url); // 添加 Query 参数 url AppendQueryParameters(url, apiConfig, parameters); // 添加 Body (如果是 POST/PUT 请求) if (apiConfig.Method POST || apiConfig.Method PUT) { request.Content CreateBodyContent(apiConfig, parameters); } // 设置公共和 API 专属 Header foreach (var header in _config.CommonHeaders) request.Headers.TryAddWithoutValidation(header.Key, header.Value); foreach (var header in apiConfig.Headers) request.Headers.TryAddWithoutValidation(header.Key, header.Value); // 添加 Authentication Token if (apiConfig.RequiresAuthentication) { var token await GetValidAccessTokenAsync(); if (token null) return ResultT.Failure(未能获取有效令牌); request.Headers.Authorization new AuthenticationHeaderValue(Bearer, token.AccessToken); } // 执行请求 var response await _httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) return ResultT.Failure(await response.Content.ReadAsStringAsync()); var responseContent await response.Content.ReadAsStringAsync(); return ResultT.Success(JsonSerializer.DeserializeT(responseContent)); } /// summary /// 替换路径中的动态参数 /// /summary private string ReplacePathParameters(string url, Dictionarystring, object parameters) { if (parameters is null) return url; foreach (var param in parameters) { var placeholder ${{{param.Key}}}; if (url.Contains(placeholder)) { url url.Replace(placeholder, param.Value.ToString()); } } return url; } /// summary /// 追加查询参数 /// /summary private string AppendQueryParameters(string url, ApiConfig apiConfig, Dictionarystring, object parameters) { var queryParams new Liststring(); foreach (var paramConfig in apiConfig.Parameters) { if (paramConfig.Location query parameters.ContainsKey(paramConfig.Name)) { queryParams.Add(${paramConfig.Name}{parameters[paramConfig.Name]}); } } if (queryParams.Any()) { var separator url.Contains(?) ? : ?; url separator string.Join(, queryParams); } return url; } /// summary /// 创建请求体数据Body /// /summary private HttpContent CreateBodyContent(ApiConfig apiConfig, Dictionarystring, object parameters) { var bodyParams parameters? .Where(p apiConfig.Parameters.Any(pc pc.Location body pc.Name p.Key)) .ToDictionary(kv kv.Key, kv kv.Value); if (apiConfig.BodyFormat application/json) { return new StringContent(JsonSerializer.Serialize(bodyParams), Encoding.UTF8, application/json); } else if (apiConfig.BodyFormat application/x-www-form-urlencoded) { return new FormUrlEncodedContent(bodyParams.ToDictionary(k k.Key, k k.Value.ToString())); } throw new NotSupportedException(不支持的 Body 格式); } /// summary /// 模拟获取有效的 AccessToken /// /summary private async TaskTokenInfo GetValidAccessTokenAsync() { // 这里可以实现从缓存或数据库中获取 token 的逻辑 return await Task.FromResult(new TokenInfo { AccessToken mocked_access_token, ExpiresAt DateTime.UtcNow.AddHours(1) }); } } } AuthProviderFactory 类 AuthProviderFactory 负责创建 AuthProvider 的实例简化多提供商的管理。 using System; using System.Collections.Generic; using System.Net.Http; using OAuth.Core.Models; namespace OAuth.Infrastructure { public class AuthProviderFactory { private readonly IDictionarystring, ProviderConfiguration _configurations; private readonly IHttpClientFactory _httpClientFactory; public AuthProviderFactory(IDictionarystring, ProviderConfiguration configurations, IHttpClientFactory httpClientFactory) { _configurations configurations ?? throw new ArgumentNullException(nameof(configurations)); _httpClientFactory httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory)); } public AuthProvider Create(string providerName) { if (!_configurations.TryGetValue(providerName, out var config)) throw new KeyNotFoundException($未找到提供商{providerName}); return new AuthProvider(_httpClientFactory.CreateClient(), config); } } } Web API 层OAuth.WebApi API 控制器 在 OAuth.WebApi 模块中我们实现了 OAuthController提供 API 的行为。 using Microsoft.AspNetCore.Mvc; using OAuth.Infrastructure; namespace OAuth.WebApi.Controllers { [Route(api/oauth)] [ApiController] public class OAuthController : ControllerBase { private readonly AuthProviderFactory _factory; public OAuthController(AuthProviderFactory factory) { _factory factory; } [HttpGet({provider}/{api})] public async TaskIActionResult ExecuteApi(string provider, string api, [FromQuery] Dictionarystring, object parameters) { var providerInstance _factory.Create(provider); var result await providerInstance.CallApiAsyncobject(api, parameters); if (!result.IsSuccess) return BadRequest(result.Error); return Ok(result.Data); } } } 配置文件示例 appsettings.json 文件配置所有可使用的 OAuth 提供商的信息。 { OAuthProviders: { WeCom: { ProviderName: WeCom, BaseUrl: https://qyapi.weixin.qq.com, AuthorizationUrl: /cgi-bin/authorize, TokenUrl: /cgi-bin/gettoken, ClientId: your-client-id, ClientSecret: your-client-secret, RedirectUri: https://your.app/wecom/callback, CommonHeaders: { User-Agent: OAuthSolution Client/1.0 }, Apis: { GetUserInfo: { Url: /cgi-bin/user/get/{userid}, Method: GET, RequiresAuthentication: true, Parameters: [ { Name: userid, Location: path } ] } } } } } 应用程序启动和配置 最后在 Program.cs 中设置 ASP.NET Core 中的依赖注入以支持我们的架构。 using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using OAuth.Core.Models; using OAuth.Infrastructure; var builder WebApplication.CreateBuilder(args); var configuration builder.Configuration; var oauthProviders configuration.GetSection(OAuthProviders).GetDictionarystring, ProviderConfiguration(); builder.Services.AddHttpClient(); builder.Services.AddSingleton(oauthProviders); builder.Services.AddSingletonAuthProviderFactory(); builder.Services.AddControllers(); var app builder.Build(); app.MapControllers(); app.Run(); 结论 通过上述方式我们构建了一个可扩展的 OAuth2 API集成方案。这种设计不仅支持多种 OAuth 提供商的接入还允许动态配置 API 的调用方式使得代码简洁明了、易于维护。未来如需引入新的提供商或 API只需在配置文件中新增相应信息即可无需对现有逻辑进行修改。 若您遇到不同 OAuth 提供商的实际需求、疑问或问题请随时在评论区留言我们将一起探讨解决方案
http://www.dnsts.com.cn/news/133379.html

相关文章:

  • 网站分享链接怎么做的购买wordpress模板
  • 上海博道投资管理公司的网站谁做的网站管理助手哪个好用
  • 东莞seo推广公司西安seo顾问
  • 小程序商城设计安新seo优化排名网站
  • 制作logo免费网站建筑企业资质公司
  • 学校网站建设 论文呢网站开发和竞价
  • 做排名的网站哪个好济南优化网站关键词
  • 番禺建设网站集团本地用织梦做网站
  • 网站服务器怎么查询昆明hph网站建设
  • wordpress安全登录插件下载失败杭州百度首页优化
  • 网站 开发 语言不拦截网页的浏览器
  • 南京驰铭做网站公司网站加速打开
  • 长春企业建站系统模板营销型网站建设报价方案
  • 电子商务网站规划建设与管理商旅100网页版
  • 安阳企业网站优化外包做网站推广的公司好做吗
  • swing做网站短视频剪辑培训班速成
  • 做网站卖货WordPress单栏二次元主题
  • 做网站小语种翻译多少钱php商城项目
  • 外贸网站外贸网站建设行吗企业为什么做网站推广
  • 网站后台框架模版深圳公司广告牌制作
  • 产业互联网平台淘宝客网站做seo
  • 长宁免费网站制作设计手机网站页面尺寸
  • 扬中网站推广托管制作团体网站
  • 广州免费自助建站平台沈阳做网站的公司排行
  • 外贸网站建设升上去呼市推广网站
  • 建设银行网站首页上海有哪些互联网公司
  • 天津网站建设信息科技有限公司农业网站建设方案 ppt
  • 韩国购物网站有哪些微信公众号app下载安装
  • 手机网站设计图尺寸域名估价哪个网站准确
  • 湖南手机网站建设公司网站设计网站项目流程