[AZ-204] Implement user authentication and authorization

Explore the Microsoft identity platform

  • Explore the Microsoft identity platform
    • Microsoft identity platform - Delegated permissions
    • OAuth 2.0 and OpenID Connect standard
  • Explore service principals
    • ถ้าจะให้การจัดการ IAM ยกไปให้ Azure Active Directory ต้อง Register Azure Active Directory tenant. โดย tenant มี 2 แบบ
      • Single tenant
      • Multi-tenant - accessible in other tenant
    • Application object - global representation of your application for use across all tenants
    • Service principal object - local representation for use in a specific tenant. / created in each tenant
      • Application - defines what the app can actually do in the specific tenant, who can access the app, and what resources the app can access.
      • Managed identity - ให้จัดการ identities to access resources. เช่น Key Vault เก็บ credentials และให้การเข้าถึง storage accounts.
      • Legacy สำหรับ App รุ่นเก่า โดยเป็น Pricipal ที่ทำก่อน App Registration
    • Relationship between application objects and service principals
      • A 1:1 relationship with the software application, and
      • A 1:many relationship with its corresponding service principal object(s).
  • Discover permissions and consent
    • Permission types
      • Delegated permissions - apps that have a signed-in user present
      • Application permissions - apps that run without a signed-in user present, background services or daemons (Administrator เท่านั้นที่ใช้งานได้)
    • Consent(ยินยอม) types นึกภาพตอนเราลง App ในมือถือ แล้วขอสิทธิเข้า Email / การโทร / ภาพถ่าย เป็นต้น
      • Static user consent
      • Incremental and dynamic user consent
      • Admin consent - high-privilege permissions
    • Requesting individual user consent
      • ยัดใส่ใน scope parameter
      • scope parameter is a space-separated list of delegated permissions that the app is requesting
  • Discover conditional access
    • เหมือน Azure AD ที่ทำ conditional access ตรวจความผิดปกติทีเกิดขึ้นจากการเข้าถึง
      เช่น IP เปลี่ยน / เข้าจาก Device ใหม่ เพื่อมาทำ Multifactor authentication
  • Knowledge check - Explore the Microsoft identity platform (Knowledge check)

Explore the Microsoft Authentication Library

  • Microsoft Authentication Library (MSAL) เป็น
    • ตัวที่ครอบ OAuth libraries (provide secure access to Microsoft Graph)
    • ไม่ต้องมาจัดการ a token cache + refreshes tokens
    • set up application from configuration files.
  • Application types and scenarios - มี Library ตามภาษา และ Platform
  • Authentication flows
  • Public client, and confidential client applications
    • Public client applications: ไม่มีการเก็บ Secret ใดๆ
    • Confidential client applications: App ที่เข้าถึงยาก อาจจะ Run บน Server ทำเก็บ application secret. ได้
  • Initialize client applications
    • application builders
      • Class PublicClientApplicationBuilder
      • Class ConfidentialClientApplicationBuilder
  • Example - PublicClientApplicationBuilder
using System;
using System.Threading.Tasks;
using Microsoft.Identity.Client;

namespace az204_auth
{
    class Program
    {
        private const string _clientId = "APPLICATION_CLIENT_ID";
        private const string _tenantId = "DIRECTORY_TENANT_ID";

        public static async Task Main(string[] args)
        {
            var app = PublicClientApplicationBuilder
                .Create(_clientId)
                .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
                .WithRedirectUri("http://localhost")
                .Build(); 
            string[] scopes = { "user.read" };
            AuthenticationResult result = await app.AcquireTokenInteractive(scopes).ExecuteAsync();

            Console.WriteLine($"Token:\t{result.AccessToken}");
        }
    }
}
  • Example - ConfidentialClientApplicationBuilder
string redirectUri = "https://myapp.azurewebsites.net";
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(clientId)
    .WithClientSecret(clientSecret)
    .WithRedirectUri(redirectUri )
    .Build();

Implement shared access signatures

  • Discover shared access signatures
    • shared access signature (SAS) is a URI that grants restricted access rights(delegate access) to Azure Storage resources
    • Types of shared access signatures
      • User delegation SAS - ใช้ Azure AD มาช่วย ทำให้ดูแลง่าย
      • Service SAS
      • Account SAS
    • Best practices
      • To securely distribute a SAS and prevent man-in-the-middle attacks, always use HTTPS.
      • The most secure SAS is a user delegation SAS. Use it wherever possible because it removes the need to store your storage account key in code. You must use Azure Active Directory to manage credentials. This option might not be possible for your solution.
      • Try to set your expiration time to the smallest useful value. If a SAS key becomes compromised, it can be exploited for only a short time.
      • Apply the rule of minimum-required privileges. Only grant the access that's required. For example, in your app, read-only access is sufficient.
      • There are some situations where a SAS isn't the correct solution. When there's an unacceptable risk of using a SAS, create a middle-tier service to manage users and their access to storage.
      • Associate SAS tokens with a stored access policy.
  • Choose when to use shared access signatures
    • แบบแรก ใช้ front-end proxy service. - ไม่ได้ใช้ SAS แต่มีข้อดี Validate ตาม Business Rule เพิ่มได้
    • แบบที่สอง A lightweight service authenticates - ใช้ SAS เข้ามาช่วย ลด Load ของ front-end proxy service.
    • แบบทื่สาม Hybrid โดยเอาแบบที่ 1 + 2
    • NOTE หากจะ Copy ข้อมูลใน Storage Account ฝั่งต้นทางต้องมีการใช้ SAS เสมอ
  • Explore stored access policies
    • นอกจาก SAS แล้ว ยังสามารถกำหนด Policy ได้ เช่น การกำหนดสิทธิ read/write ที่ blob storage ให้ expire หลังจากได้รับสิทธิไป 1 ชั่วโมง เป็นต้น
    • กำหนดจาก Code
BlobSignedIdentifier identifier = new BlobSignedIdentifier
{
    Id = "stored access policy identifier",
    AccessPolicy = new BlobAccessPolicy
    {
        ExpiresOn = DateTimeOffset.UtcNow.AddHours(1),
        Permissions = "rw"
    }
};

blobContainer.SetAccessPolicy(permissions: new BlobSignedIdentifier[] { identifier });
  • กำหนดจาก CLI
az storage container policy create \
    --name <stored access policy identifier> \
    --container-name <container name> \
    --start <start time UTC datetime> \
    --expiry <expiry time UTC datetime> \
    --permissions <(a)dd, (c)reate, (d)elete, (l)ist, (r)ead, or (w)rite> \
    --account-key <storage account key> \
    --account-name <storage account name> \
  • Modifying or revoking a stored access policy
    • Revoke - ลบ Policy ออกไป หรือ แก้ได้ Expire time หรือ ส่งตัว Policy (API ให้ส่ง Request Body เก็บค่าว่างไป)
    • Modify - แก้ไขสิทธิ กำหนดสิทธิใหม่ แล้ว
  • Knowledge check - Implement shared access signatures (Knowledge check)

Explore Microsoft Graph

  • Discover Microsoft Graph
    • Microsoft Graph facilitates the access and flow of data and how to form queries through REST and code.
    • main components
      • Microsoft Graph API (https://graph.microsoft.com) ใช้ REST API / SDK เขียน Code มาเชื่อมต่อ เพื่อจัดการ Device / Identity / Access / Compliance / Security
      • Microsoft Graph connectors - เอาExternal Data Source เข้า MS Graph API
      • Microsoft Graph Data Connect -
  • Query Microsoft Graph by using REST
    • Version - v1.0  พร้อมใช้งาน / beta สำหรับ Preview Feature
    • Resource -
    • Query parameters
      • OData system query options
      • String Param
      • ยกตัวอย่าง เช่น เพิ่ม filter=emailAddress eq 'jon@contoso.com'
#Template
{HTTP method} https://graph.microsoft.com/{version}/{resource}?{query-parameters}

#Example
GET https://graph.microsoft.com/v1.0/me/messages?filter=emailAddress eq 'jon@contoso.com'

Note

  • Permission
    • Microsoft Graph API > User.Read / Delegation
    • Azure Storage API > user_impersonation

Reference


Discover more from naiwaen@DebuggingSoft

Subscribe to get the latest posts sent to your email.