当Authorize标记不包含角色时,我没有得到一个范围复选框,Ajax授权请求也没有发送范围

本文关键字:范围 一个 复选框 请求 Ajax 授权 Authorize 包含 角色 | 更新日期: 2023-09-27 18:09:00

UPDATE 2:如果我从这个

改变我的控制器授权标签
[Authorize]

[Authorize(Roles = "Read")]

,然后我得到用于范围选择的复选框,ajax令牌请求包含正确的范围并成功完成。然而,我最后还是用了一个红色的感叹号。看起来Swagger或Swashbuckle要求角色匹配作用域定义?在使用Swashbuckle时,是否可以使用没有定义role的应用程序流?如果是这样,你怎么让它工作呢?我必须在操作过滤器类中手动设置作用域吗?如果不在授权标记中列出角色就不可能使用Swashbuckle,那么我需要知道如何在IdentityServer3中分配客户端角色。

更新3 如果我将Operation Filter更改为类似的内容,则显示范围,但是在选择范围并单击Authorize之后,页面只是重新加载。ajax授权发送成功。处理步骤这个更接近,但是授权仍然不持久(不确定在这里使用哪个术语,但是"持久"似乎概括了它)。我怎样才能获得粘贴的授权?

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
    var scopes = new List<string>() { "Read" };
    if (scopes.Any())
    {
        if (operation.security == null)
            operation.security = new List<IDictionary<string, IEnumerable<string>>>();
        var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
        {
            { "oauth2", scopes }
        };
        operation.security.Add(oAuthRequirements);
    }
}

原始文章我正在尝试配置Swashbuckle,以允许客户端测试受OAuth2客户端凭证流保护的REST服务。这个开关永远不会出现在页面上,应该吗?,但我确实得到一个带感叹号的红色圆圈,告诉我资源不受保护。我用的是金块包Swashbuckle。核心版本5.4.0。在Swashbuckle中启用Oauth2客户端凭证流的答案似乎遵循了我所做的,并逐字使用了AssignOAuth2SecurityRequirements类。我没有注入任何javascript,也不认为我必须这样做,因为我的授权方案是相当标准的。当我删除控制器上的Authorize关键字时,该方法在Swagger UI中不再有红色感叹号,我希望这意味着我很接近,但我没有找到缺失的链接。因为这个流是"应用程序",我只有一个作用域,我想确保它看起来配置正确,clientSecret被加载在正确的位置。

更新1我已经能够调试AJAX调用,并且可以看到没有设置范围,因此没有在请求中发送。为什么没有设置作用域?为什么没有一个复选框来选择作用域?

这是我的SwaggerConfig.cs

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;
        GlobalConfiguration.Configuration
            .EnableSwagger(c =>
            {
                c.SingleApiVersion("v1", "waRougeOneApp");
                c.OAuth2("oauth2")
                    .Description("OAuth2 Client Credentials Grant Flow")
                    .Flow("application")
                    .TokenUrl("https://securitydev.rougeone.com/core/connect/token")
                    .Scopes(scopes =>
                    {
                        scopes.Add("Read", "Read access to protected resources");
                    });
                c.IncludeXmlComments(GetXmlCommentsPath());
                c.UseFullTypeNameInSchemaIds();
                c.DescribeAllEnumsAsStrings();
                c.OperationFilter<AssignOAuth2SecurityRequirements>();
            })
            .EnableSwaggerUi(c =>
            {
                c.EnableOAuth2Support(
                    clientId: "client_id",
                    clientSecret: "client_secret",
                    realm: "swagger-realm",
                    appName: "Swagger UI"
                );
            });
    }
    protected static string GetXmlCommentsPath()
    {
        return System.String.Format(@"{0}bin''waRougeOne.xml", System.AppDomain.CurrentDomain.BaseDirectory);
    }
}
AssignOAuth2SecurityRequirements类是
public class AssignOAuth2SecurityRequirements : IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var authorized = apiDescription.ActionDescriptor.GetCustomAttributes<AuthorizeAttribute>();
        if (!authorized.Any()) return;
        if (operation.security == null)
            operation.security = new List<IDictionary<string, IEnumerable<string>>>();
        var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
  {
      {"oauth2", Enumerable.Empty<string>()}
  };
        operation.security.Add(oAuthRequirements);
    }
}

我一直试图找到一个工作的例子,客户端凭证流没有成功,所以我不是100%肯定,当一切正常工作时,我会看到一个切换按钮。在隐式流程的示例中,如果将鼠标悬停在红色感叹号圈上,您将看到列出的授权类型,单击红色感叹号圈将显示列出的范围的选项,您可以在其中选择一个,然后单击授权,然后返回一个蓝色感叹号。

对于我来说,我从来没有得到一个复选框来选择一个范围,但我只定义了一个范围。我做错了什么?我在调试swagger ui JavaScript时发现了这一点,它似乎指向拥有所需的所有数据?

authorizations
:
null
auths
:
Array[1]
0
:
Object
name
:
"oauth2"
type
:
"oauth2"
value
:
Object
description
:
"OAuth2 Client Credentials Grant Flow"
flow
:
"application"
scopes
:
Object
Read
:
"Read access to protected resources"
__proto__
:
Object
tokenUrl
:
"https://security.starrwarrs.com/core/connect/token"
type
:
"oauth2"
__proto__
:
Object
__proto__
:
Object
length
:
1
__proto__
:
Array[0]

当Authorize标记不包含角色时,我没有得到一个范围复选框,Ajax授权请求也没有发送范围

解决方案!!最后一部分是最难弄清楚的,我最终在Chrome Developer工具的帮助下完成了这一点,它在网络标签上显示了一个红色的小X,显示了以下错误信息:

XMLHttpRequest cannot load http://security.RogueOne.com/core/connect/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:62561' is therefore not allowed access.

错误消息最终连接了下面的点,在此之前将调用on OAuthComplete完整JavaScript函数,但没有令牌。网络选项卡显示"此请求没有可用的响应数据",但我会在响应头中看到内容类型为Json的Content-Length。Fiddler还显示了响应,它看起来像(并且是)格式良好的JSON。

我在这里描述了这个错误Swagger UI没有解析响应,这是由于IdentityServer3正确地没有添加响应头"Access-Control-Allow-Origin:http://localhost:62561",你可以通过更新你的客户端创建来强制IdentityServer3发送该头:

new Client
{
    ClientName = "SwaggerUI",
    Enabled = true,
    ClientId = "swaggerUI",
    ClientSecrets = new List<Secret>
    {
        new Secret("PasswordGoesHere".Sha256())
    },
    Flow = Flows.ClientCredentials,
    AllowClientCredentialsOnly = true,
    AllowedScopes = new List<string>
    {
        "Read"
    },
    Claims = new List<Claim>
    {
        new Claim("client_type", "headless"),
        new Claim("client_owner", "Portal"),
        new Claim("app_detail", "allow")
    },
    PrefixClientClaims = false
    // Add the AllowedCorOrigins to get the Access-Control-Allow-Origin header to be inserted for the following domains
    ,AllowedCorsOrigins = new List<string>
    {
        "http://localhost:62561/"
        ,"http://portaldev.RogueOne.com"
        ,"https://portaldev.RogueOne.com"
    }
}    

allowedcororigin是我拼图的最后一块。希望这能帮助到遇到同样问题的人

这些是我们已经完成和工作的步骤:

  1. 在SwaggerConfig文件中,添加以下设置:
c.OAuth2("oauth2")
 .Description("OAuth2 Implicit Grant") 
 .Flow("implicit")
 .AuthorizationUrl(swaggerConfigurations["IssuerUri"].ToString())
 .Scopes(scopes =>
  {
    scopes.Add("user_scope", "Access REST API");
  });

属性为:

  • 授权方案的名称(上面示例中的oauth2)
  • 授权方案描述信息
  • Flow -授予的类型
  • 授权Url -应该是身份管理系统Url的授权Url(例如:https://auth2.test.com/oauth2/authorize)
  • 作用域-作用域名称

二世。在SwaggerConfig文件中,在swagger ui配置部分下添加以下设置:

c.EnableOAuth2Support(swaggerConfigurations["ClientId"].ToString(), string.Empty, swaggerConfigurations["RedirectUri"].ToString(), "Swagger", " ", new Dictionary<string, string> { { "resource", GetResources() } });

方法接受以下参数:

  • clientId -这应该是在安全令牌服务
  • 中配置的swagger的客户端ID
  • clientSecret -这应该是客户端的秘密密钥。只有在代码授予类型
  • 的情况下才需要这样做。
  • realm -这应该是重定向url(这应该是[base address] + swagger/ui/o2c-html)
  • appName -这应该是swagger
  • scopesoperator—如果只有
  • 范围,则不需要传递该参数。
  • additionalQueryStringParams -这应该有有效受众的列表,这对应于发出令牌的资源。

III。在web api项目中创建一个新的Operation Filter,如下所示:

public class CustomOperationFilter : IOperationFilter
    {              
        public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
        {     
            string clientId = "clientID";
            if (apiDescription != null)
            {
                var actFilters = apiDescription.ActionDescriptor.GetFilterPipeline();
                var allowsAnonymous = actFilters.Select(f => f.Instance).OfType<OverrideAuthorizationAttribute>().Any();
                if (allowsAnonymous)
                {
                    return; // must be an anonymous method
                }
            }
            if (operation != null)
            {
                if (operation.security == null)
                {
                    operation.security = new List<IDictionary<string, IEnumerable<string>>>();
                }
                var authRequirements = new Dictionary<string, IEnumerable<string>>
                {
                    { "oauth2", new List<string> { clientId } }
                };
                operation.security.Add(authRequirements);
            }
        }
    }

该类将用于将OAuth范围绑定到各个操作

第四。在swagger配置文件中添加上述过滤器(参见下面的代码)

c.OperationFilter<CustomOperationFilter>();

V。在安全令牌服务中配置客户端ID、Secret、重定向Url和资源

VI。在Web API项目中,如果使用index.html注入API特定的UI字段/样式,那么请确保所有javascript代码与index.html文件的Swashbuckle版本保持完整(在位置- https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/SwaggerUi/CustomAssets/index.html中提供)