使用.NET 4.5使用IdentityServer3对Swagger进行身份验证



我遇到一些问题,可以与OAuth2一起工作。我在数据库中创建了一个客户端:

private static void CreateSwaggerClient(DatabaseContext context)
{
    var client = new Client
    {
        ClientId = "swaggerui",
        ClientName = "Swagger UI client",
        Flow = Flows.Implicit,
        Enabled = true,
        EnableLocalLogin = true,
        AccessTokenType = AccessTokenType.Reference,
        AllowAccessTokensViaBrowser = true,
        IdentityTokenLifetime = 300,
        AccessTokenLifetime = 3600,
        AuthorizationCodeLifetime = 300,
        AbsoluteRefreshTokenLifetime = 2592000,
        SlidingRefreshTokenLifetime = 1296000,
        RedirectUris = new List<ClientRedirectUri>
        {
            new ClientRedirectUri { Uri = "http://localhost:62668/swagger" }
        },
        AllowedScopes = new List<ClientScope>()
        {
            new ClientScope
            {
                Scope = "api"
            }
        },
        ClientSecrets = new List<ClientSecret>()
        {
            new ClientSecret
            {
                Value = "secret".Sha256(),
                Type = "SharedSecret"
            }
        }
    };
    context.Clients.Add(client);
    context.SaveChanges();
}

可以访问我的 API 范围:

private static void CreateScope(DatabaseContext context)
{
    var scope = new Scope
    {
        Enabled = true,
        Name = "api",
        DisplayName = "Cormar API",
        Description = "Should only be used for trusted internal service side applications",
        Required = true,
        Emphasize = true,
        Type = (int)ScopeType.Resource,
        IncludeAllClaimsForUser = false,
        ShowInDiscoveryDocument = true,
        AllowUnrestrictedIntrospection = true,
        ScopeClaims = new List<ScopeClaim>()
        {
            new ScopeClaim
            {
                Name = "role",
                Description = "Role claim types",
                AlwaysIncludeInIdToken = true
            },
            new ScopeClaim
            {
                Name = "name",
                Description = "The name of the user",
                AlwaysIncludeInIdToken = true
            },
            new ScopeClaim
            {
                Name ="password",
                Description = "Contains the encrypted password for a user",
                AlwaysIncludeInIdToken = true
            }
        },
        ScopeSecrets = new List<ScopeSecret>()
        {
            new ScopeSecret
            {
                Value = "anothersecret".Sha256(),
                Type = "SharedSecret"
            } 
        }
    };
    context.Scopes.Add(scope);
    context.SaveChanges();
}

如果我打开浏览器并导航到这样的授权URL:https://localhost:44313/dissentity/connect/授权?client_id = swaggerui&redirect_uri = http:http://localhost:62668/swagger_tagger&wenspys_tagger&wenspys_tepe_type = tokepe = token&amp = token&amp = token&amp; scope = api&amp; state = moo,它将带我进入登录页面,当我输入用户名和密码时,我将我带到Swagger页面上,然后使用 access_token 将其添加到URL上:

#access_token=b49fe5641519c325c17d248d2372d69f&token_type=Bearer&expires_in=3600&scope=api&state=moo

但是,这里的问题是,如果我单击任何内容,则将访问令牌从URL中删除,如果我尝试任何端点,它们都会失败而拒绝访问。我已经设置了这样的招摇配置:

private static void ConfigureSwagger(HttpConfiguration config)
{
    config.EnableSwagger(c =>
    {
        c.SingleApiVersion("v1", "test API");
        var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        var commentsFileName = Assembly.GetExecutingAssembly().GetName().Name + ".XML";
        var commentsFile = Path.Combine(baseDirectory, "bin", commentsFileName);
        c.IncludeXmlComments(commentsFile);
        c.OAuth2("oauth2")
            .Description("OAuth2 Implicit Grant")
            .Flow("implicit")
            .AuthorizationUrl("http://localhost:62668/identity/connect/authorize")
            .TokenUrl("http://localhost:62668/identity/connect/token")
            .Scopes(scopes =>
            {
                scopes.Add("api", "api access");
            });
        c.OperationFilter<AssignOAuth2SecurityRequirements>();
    }).EnableSwaggerUi(c =>
    {
        c.EnableOAuth2Support("swaggerui", "secret", "local", "test");
    });
}

谁能告诉我我缺少什么?

我设法使此工作。首先,我的AssignOAuth2SecurityRequirements设置不正确。我实际上在这里找到了正确的代码:http://knowyourtoolset.com/2015/08/secure-web-apis-with-with-swagger-swashbuckle-swashbuckle-and-oauth2-part-part-2/

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<OverrideAuthorizationAttribute>().Any();
        if (allowsAnonymous)
            return; // must be an anonymous method

        //var scopes = apiDescription.ActionDescriptor.GetFilterPipeline()
        //    .Select(filterInfo => filterInfo.Instance)
        //    .OfType<AllowAnonymousAttribute>()
        //    .SelectMany(attr => attr.Roles.Split(','))
        //    .Distinct();
        if (operation.security == null)
            operation.security = new List<IDictionary<string, IEnumerable<string>>>();
        var oAuthRequirements = new Dictionary<string, IEnumerable<string>>
    {
        {"oauth2", new List<string> {"api"}}
    };
        operation.security.Add(oAuthRequirements);
    }
}

接下来,我的客户的 redirect_uris 不正确。它们都必须是 https ,并且需要完整的重定向URI。我的成为这个:

new ClientRedirectUri { Uri = "https://localhost:44313/swagger/ui/o2c-html" },

设置这些设置后,所有这些都开始工作。

最新更新