博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET WebAPI 集成 Swagger 启用 OAuth 2.0 配置问题
阅读量:7155 次
发布时间:2019-06-29

本文共 5693 字,大约阅读时间需要 18 分钟。

在 ASP.NET WebAPI 集成 后,由于接口使用了 做的认证,调试起来很不方便;看了下 的文档 ,是支持 OAuth2.0 的配置的,使用的简化模式(Implicit grant type),交互的流程如下:

Implicit Grant Type (简化模式)

参数:

  • response_type:表示授权类型,此处的值固定为"token",必选项。
  • client_id:表示客户端的ID,必选项。
  • redirect_uri:表示重定向的URI,可选项。
  • scope:表示权限范围,可选项。
  • state:表示客户端的当前状态,可以指定任意值,认证服务器会原封不动地返回这个值。
GET /authorize?response_type=token&client_id=s6BhdRkqt3&state=xyz        &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.1    Host: server.example.com

认证服务器回应客户端的URI,包含以下参数:

  • access_token:表示访问令牌,必选项。
  • token_type:表示令牌类型,该值大小写不敏感,必选项。
  • expires_in:表示过期时间,单位为秒。如果省略该参数,必须其他方式设置过期时间。
  • scope:表示权限范围,如果与客户端申请的范围一致,此项可省略。
  • state:如果客户端的请求中包含这个参数,认证服务器的回应也必须一模一样包含这个参数。

     HTTP/1.1 302 Found

     Location: #access_token=2YotnFZFEjr1zCsicMWpAA
               &state=xyz&token_type=example&expires_in=3600

Swagger 启用 OAuth 2.0 配置

Idrv 中配置客户端(Client)

new Client                {                    ClientName = "Test_API_Flow",                    ClientId = "api_test_api_flow",                    Flow = Flows.Implicit,                    ClientUri = "https://identityserver.io",                    RequireConsent = true,                    AllowRememberConsent = true,                    RedirectUris = new List
{ "http://localhost:39106/swagger/ui/o2c-html", }, AllowedCorsOrigins = new List
{ "http://localhost:39106" }, AccessTokenLifetime = 3600, AccessTokenType = AccessTokenType.Jwt, AllowAccessToAllScopes=true },

API:

app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions            {                Authority = IdsvSetting.Authority,                ValidationMode = ValidationMode.ValidationEndpoint,                RequiredScopes=new List
{
"all","user","order"}} });
///     /// 早餐控制器    ///     [RoutePrefix("api/v1/breakfast")]    public class BreakfastController : ApiController    {        private static readonly Logger logger = LogManager.GetCurrentClassLogger();        ///         /// 早餐服务        ///         private readonly IBreakfastService _breakfastService;        ///         /// 构造方法        ///         /// 早餐服务        public BreakfastController(IBreakfastService breakfastService)        {            _breakfastService = breakfastService;        }        #region 获得酒店关联的餐厅的酒店        ///         /// 获得酒店关联的餐厅的酒店        ///         /// 酒店编号        /// 
获得酒店关联的餐厅的酒店
[Authorize] [HttpGet] [Route("{hotelcd}/mapping")] public async Task
GetXhotelBreakfastHotelMappingRequest(string hotelcd) { var response = await _breakfastService.GetXhotelBreakfastHotelMappingRequest(hotelcd); return Json(response); } #endregion }}

配置 SwaggerConfig

//https://tsso.xxx.cn/connect/authorize?response_type=token&redirect_uri=http%3A%2F%2Flocalhost%3A39106%2Fswagger%2Fui%2Fo2c-html&realm=test-realm&client_id=api_test_api_flow&scope=all%20%20&state=oauth2                        c.OAuth2("oauth2")                            .Description("OAuth2 Implicit Grant")                            .Flow("implicit")                            .AuthorizationUrl("https://tsso.xxx.cn/connect/authorize")                            //.TokenUrl("https://sso.xxx.cn/connect/token")                            .Scopes(scopes =>                            {                                scopes.Add("all", "all access to protected resources");                                scopes.Add("user", "user access to protected resources");                                scopes.Add("order", "order access to protected resources");                            });...       c.OperationFilter
(); c.EnableOAuth2Support( clientId: "api_test_api_flow", clientSecret: null, realm: "test-realm", appName: "Swagger UI" //additionalQueryStringParams: new Dictionary
() { { "foo", "bar" } } );
public class AssignOAuth2SecurityRequirements : IOperationFilter        {            public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)            {                var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();                var allowsAnonymous = actFilters.Select(f => f.Instance).OfType
().Any(); if (allowsAnonymous) return; // must be an anonymous method //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline() // .Select(filterInfo => filterInfo.Instance) // .OfType
() // .SelectMany(attr => attr.Roles.Split(',')) // .Distinct(); if (operation.security == null) operation.security = new List
>>(); var oAuthRequirements = new Dictionary
> { {
"oauth2", new List
{ "all","user","order"}} }; operation.security.Add(oAuthRequirements); } }

OK ,配置完成,点击红色的圈圈,登录成功会302到  上

当然也可以退出授权:

REFER:

https://www.scottbrady91.com/Identity-Server/ASPNET-Core-Swagger-UI-Authorization-using-IdentityServer4

转载地址:http://ivegl.baihongyu.com/

你可能感兴趣的文章
vs2015 + opencv3.4.0 + qt msvc2015_64-5.7.1
查看>>
[c语言]左移和右移
查看>>
[HAOI2008]排名系统 & [Zjoi2006]GameZ游戏排名系统 BZOJ1862&BZOJ1056
查看>>
电子商城实录------载入数据库模型
查看>>
iOS上的反射用法
查看>>
python之路-09-文件操作
查看>>
Linux常用命令大全
查看>>
链表API
查看>>
table中绝对定位元素相对td定位失效解决方案
查看>>
打印和显示特殊需求
查看>>
python实现二分查找算法
查看>>
NYOJ747
查看>>
结构体之间的转换
查看>>
Oracle中逻辑结构图解
查看>>
java08双重循环打印图形
查看>>
面向对象03
查看>>
融资融券委托业务
查看>>
CSS实现太极图(3个div实现)
查看>>
windows环境中JDK环境变量配置
查看>>
HDU2629 Identity Card【MAP+水题】
查看>>