개발이야기/AspNet&C#

IdentityServer 학습 #7 - API access

Roslyn 2024. 3. 7. 16:18
반응형

API access 관련 내용을 다음과 같이 정리합니다.

원문링크 : https://docs.duendesoftware.com/identityserver/v7/quickstarts/3_api_access/

 

(1) 새롭게 추가할 스코프를 정의해 줍니다. (중요! 원문에서 누락된 부분)

    public static IEnumerable<IdentityResource> IdentityResources =>
        new IdentityResource[]
        { 
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
            new IdentityResource()
            {
                Name = "verification",
                UserClaims = new List<string>
                {
                    JwtClaimTypes.Email,
                    JwtClaimTypes.EmailVerified
                }
            }
        };

 

위와 같이 추가할 verification scope에 대해 정의를 해줘야 합니다.

필자의 경우, 원문에 저 내용이 누락되어 있어 문제를 찾는데 한참 걸렸습니다. ㅠㅠ

이 내용은 이후에 진행되는 단계인 Asp.net Core Identity 에서 확인할 수 있습니다.

 

(2) 기존에 정의되어 있는 Client에 추가된 scope를 Allowed 시켜주고, OfflineAccess를 true로 활성화 해줍니다.

        new Client
        {
            ClientId = "web",
            ClientSecrets = { new Secret("secret".Sha256()) },

            AllowedGrantTypes = GrantTypes.Code,
            
            // where to redirect to after login
            RedirectUris = { "https://localhost:5002/signin-oidc" },

            // where to redirect to after logout
            PostLogoutRedirectUris = { "https://localhost:5002/signout-callback-oidc" },

            AllowOfflineAccess = true,

            AllowedScopes =
            {
                IdentityServerConstants.StandardScopes.OpenId,
                IdentityServerConstants.StandardScopes.Profile,
                "verification",
                "api1"
            }
        }

 

이렇게 AllowOfflineAccess를 활성화 함으로써, 사용자가 로그아웃을 하더라도, 여전히 토큰을 이용할 수 있습니다.

아직 사용할 수 있는 토큰은 로그아웃 후에도, 사용자 정보를 수집하거나 필요한 작업을 수행할 수 있습니다.

 

(3) 이번에는 API 서버쪽에서 Program.cs 파일을 수정하여 추가된 Scope를 명시합니다.

builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = "Cookies";
    options.DefaultChallengeScheme = "oidc";
})
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "https://localhost:5001";

        options.ClientId = "web";
        options.ClientSecret = "secret";
        options.ResponseType = "code";

        options.SaveTokens = true;

        options.Scope.Clear();
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.Scope.Add("api1");
        options.Scope.Add("offline_access");
        options.Scope.Add("verification");
        options.ClaimActions.MapJsonKey("email_verified", "email_verified");
        options.GetClaimsFromUserInfoEndpoint = true;

        options.MapInboundClaims = false; // Don't rename claim types

        options.SaveTokens = true;
    });

 

(4) 이제 WebClient 프로젝트에 페이지 하나를 추가하여, 인증정보를 출력하도록 만듭니다.

public class CallApiModel : PageModel
{
    public string Json = string.Empty;

    public async Task OnGet()
    {
        var accessToken = await HttpContext.GetTokenAsync("access_token");
        var client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
        var content = await client.GetStringAsync("https://localhost:6001/identity");

        var parsed = JsonDocument.Parse(content);
        var formatted = JsonSerializer.Serialize(parsed, new JsonSerializerOptions { WriteIndented = true });

        Json = formatted;
    }
}

 

@page
@model MyApp.Namespace.CallApiModel

<pre>@Model.Json</pre>

 

(5) 로그인하여 해당 페이지로 이동해 보면 다음과 같이 정보가 표시됩니다.

반응형