• システム開発に関わる内容をざっくりと書いていく

IdentityServer4へのクライアント追加手順(Swagger版)

・IdentityServer側

ApiScopeへの追加

Config.cs

//scope名-Disp名
new ApiScope("testms", "Access to TestMS API"),

ApiResourceへの追加

Config.cs

//API名-Disp名
new ApiResource("testmsapi", "TestMS API")
{
    //scope名
    Scopes = { "testms" }
}

Clientの追加

Config.cs

new Client
{
    //id
    ClientId = "testmsswaggerui",
    //表示名
    ClientName = "TestMS Swagger UI",
    //暗黙 更新トークン等の高度な機能は無
    AllowedGrantTypes = GrantTypes.Implicit,
    //クライアントがブラウザを介してアクセストークンを受信できるようにするかどうか
    AllowAccessTokensViaBrowser = true,
    //トークンまたは認証コードを返すことができるURI
    RedirectUris = { $"{configuration["TestMSApiUrlExternal"]}/swagger/oauth2-redirect.html" },
    //ログアウト後にリダイレクトできるURI
    PostLogoutRedirectUris = { $"{configuration["TestMSApiUrlExternal"]}/swagger/" },
    //対応するスコープ名を追加して、許可されるリソースを指定
    AllowedScopes =
    {
        "testms"
    }
}

・Client側

Swaggerに認証の追加

Startup.cs-ConfigureServices(IServiceCollection services)

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnDapr - TestMSApi", Version = "v1" });

    //identityUrl
    var identityUrlExternal = Configuration.GetValue<string>("IdentityUrlExternal");
    //AddSecurityDefinition
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows()
        {
            Implicit = new OpenApiOAuthFlow()
            {
                //IdentityUrl Authorization
                AuthorizationUrl = new Uri($"{identityUrlExternal}/connect/authorize"),
                //IdentityUrl Token
                TokenUrl = new Uri($"{identityUrlExternal}/connect/token"),
                //Scope
                Scopes = new Dictionary<string, string>()
                {
                    //Scope名   任意の説明
                    { "testms", "TestMS API" }
                }
            }
        }
    });
    //OperationFilter
    c.OperationFilter<AuthorizeCheckOperationFilter>();
});

AuthorizeCheckOperationFilterの追加

AuthorizeCheckOperationFilter .cs

public class AuthorizeCheckOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        // Check for authorize attribute
        var hasAuthorize = context.MethodInfo.DeclaringType.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any() ||
                           context.MethodInfo.GetCustomAttributes(true).OfType<AuthorizeAttribute>().Any();

        if (!hasAuthorize) return;

        operation.Responses.TryAdd("401", new OpenApiResponse { Description = "Unauthorized" });
        operation.Responses.TryAdd("403", new OpenApiResponse { Description = "Forbidden" });

        var oAuthScheme = new OpenApiSecurityScheme
        {
            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" }
        };

        operation.Security = new List<OpenApiSecurityRequirement>
            {
                new OpenApiSecurityRequirement
                {
                    [ oAuthScheme ] = new [] { "testmsapi" }
                }
            };
    }
}

AddAuthentication(認証)の追加

Startup.cs-ConfigureServices(IServiceCollection services)

services.AddAuthorization(options =>
    {
        options.AddPolicy("ApiScope", policy =>
        {
            policy.RequireAuthenticatedUser();
            policy.RequireClaim("scope", "testms");
        });
    });

AddAuthorization(認可)の追加

Startup.cs-ConfigureServices(IServiceCollection services)

services.AddAuthorization(options =>
    {
        options.AddPolicy("ApiScope", policy =>
        {
            policy.RequireAuthenticatedUser();
            //claimType=scope scope名=testms
            policy.RequireClaim("scope", "testms");
        });
    });

SwaggerにUIの追加

Startup.cs- Configure(IApplicationBuilder app)

app.UseSwagger();
app.UseSwaggerUI(c => 
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "TestMSApi v1");
    //IdentityServerのClientID
    c.OAuthClientId("testmsswaggerui");
    //IdentityServerのClientName
    c.OAuthAppName("TestMS Swagger UI");
});

認証認可の追加

Startup.cs- Configure(IApplicationBuilder app)

app.UseAuthentication();
app.UseAuthorization();