简体   繁体   English

使用.net 4.5与Identityserver3验证swagger

[英]Authenticating swagger with identityserver3 using .net 4.5

I am having some issues getting swagger to work with oauth2. 我遇到一些麻烦,无法使用oauth2。 I have created a client in my database like this: 我在数据库中创建了一个客户端,如下所示:

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

Which has access to my api Scope: 可以访问我的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();
}

If I open a browser and navigate to the authorize url like this: https://localhost:44313/identity/connect/authorize?client_id=swaggerui&redirect_uri=http://localhost:62668/swagger&response_type=token&scope=api&state=moo it takes me to a login page, which when I type the username and password brings me to the swagger page with a access_token appended to the URL like this: 如果我打开浏览器并导航到这样的授权URL: https:// localhost:44313 / identity / connect / authorize?client_id = swaggerui&redirect_uri = http:// localhost:62668 / swagger&response_type = token&scope = api&state = moo进入登录页面,当我输入用户名和密码时,将其带到URL后面的access_token的粗体页面,如下所示:

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

But the issue here is that if I click anything, the access token is removed from the url and if I try any of my endpoints, they all fail with access denied. 但是这里的问题是,如果我单击任何按钮,访问令牌将从URL中删除,并且如果我尝试任何端点,它们都将失败,并且访问被拒绝。 I have setup my swagger config like this: 我已经像这样设置了我的招摇配置:

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

Can anyone tell me what I am missing? 谁能告诉我我想念的东西吗?

I managed to get this working. 我设法使这个工作。 First of all, my AssignOAuth2SecurityRequirements was setup incorrectly. 首先,我的AssignOAuth2SecurityRequirements设置不正确。 I actually found the right code here: http://knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-part-2/ 我实际上在这里找到了正确的代码: http : //knowyourtoolset.com/2015/08/secure-web-apis-with-swagger-swashbuckle-and-oauth2-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);
    }
}

Next, the redirect_uris for my client were incorrect. 接下来,我的客户端的redirect_uris不正确。 They all have to be https and they need the full redirect uri. 它们都必须是https ,并且需要完整的重定向uri。 Mine became this: 我的变成了:

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

Once these were set up, it all started working. 设置好这些之后,它们便开始工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM