I'm not getting a scope checkbox when the Authorize tag doesn't contain roles, Ajax authorization request not sending scope either

后端 未结 2 1736
执笔经年
执笔经年 2021-01-22 19:21

UPDATE 2: If I change my controller Authorize tag from this

[Authorize]

to this

[Authorize(Roles = \"Read\")]
         


        
相关标签:
2条回答
  • 2021-01-22 19:40

    These are the steps which we have done and worked:

    1. In the SwaggerConfig file, add the below settings:
    c.OAuth2("oauth2")
     .Description("OAuth2 Implicit Grant") 
     .Flow("implicit")
     .AuthorizationUrl(swaggerConfigurations["IssuerUri"].ToString())
     .Scopes(scopes =>
      {
        scopes.Add("user_scope", "Access REST API");
      });
    

    The attributes are:

    • Name of the authorization scheme (oauth2 in the above sample)
    • Description of the authorization scheme
    • Flow – Type of grant to be used
    • Authorization Url – Should be the Auth Url of identity management system url (eg: https://auth2.test.com/oauth2/authorize)
    • Scopes – The scope name

    II. In the SwaggerConfig file, add the below settings also under the swagger ui configuration section:

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

    The method accepts the below parameters:

    • clientId – This should be client ID for swagger configured in Security Token Service
    • clientSecret – This should be client secret key. This is required only in case of Code grant type
    • realm – This should be the redirect url (this should be [base address] + swagger/ui/o2c-html)
    • appName – This should be swagger
    • scopeSeperator – This is not required to be passed if there is only scope
    • additionalQueryStringParams – This should have the list of valid audiences and this corresponds to the resource for which the token is issued.

    III. Create a new Operation Filter in the web api project as shown below:

    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);
                }
            }
        }
    

    This class will be used to bind the OAuth scopes to the individual operations

    IV. Add the above filter in the swagger config file (see code below)

    c.OperationFilter<CustomOperationFilter>();
    

    V. Configure the Client ID, Secret, Redirect Url and Resource in Security Token Service

    VI. In the Web API project, if there is an index.html being used to inject API specific UI fields/styles, then make sure that all the javascript code is kept intact with the Swashbuckle version of the index.html file (as provided in the location - https://github.com/domaindrivendev/Swashbuckle/blob/master/Swashbuckle.Core/SwaggerUi/CustomAssets/index.html)

    0 讨论(0)
  • 2021-01-22 20:03

    Solution!! The last part was the hardest to figure out, which I finally did with the help of the Chrome Developer tools that showed a little red X on the network tag showing the following error message:

    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.
    

    The error message finally connected the dots below, until then the on OAuthComplete complete JavaScript function would be called, but with no token. The network tab show "This request has no response data available", but I'd see a Content-Length in the Response headers with a content-type of Json. Fiddler also showed the response which looked like (and was) well formed JSON.

    I described this error here Swagger UI not parsing reponse which was due to IdentityServer3 correctly not adding a response header of "Access-Control-Allow-Origin:http://localhost:62561" You can force IdentityServer3 to send that header by updating you client creation to be the following:

    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"
        }
    }    
    

    The AllowedCorsOrigins was the last piece of my puzzle. Hopefully this helps someone else who is facing the same issue

    0 讨论(0)
提交回复
热议问题