使用 Remix-AuthRemix 的 MicrosoftStrategy

Microsoft 策略用於透過 Remix Auth,針對 Microsoft Active Directory 上的帳戶驗證使用者。這可以是工作/學校帳戶或個人 Microsoft 帳戶,例如 Skype、Xbox 和 Outlook.com。它擴展了 remix-auth-oauth2 策略。

支援的執行環境

執行環境 是否支援
Node.js
Cloudflare

如何使用

建立 OAuth 應用程式

依照 Microsoft 文件上的步驟建立新的應用程式註冊。您應該選擇 Web 作為平台,設定一個重新導向 URI,並新增一個用戶端密碼。

If you want to support login with both personal Microsoft accounts and school/work accounts, you might need to configure the supported account types by editing the manifest file. Set `signInAudience` value to `MicrosoftADandPersonalMicrosoftAccount` to allow login also with personal accounts.

如果在本機執行,請將重新導向 URI 變更為 https://example.com/auth/microsoft/callbackhttps://127.0.0.1:4200/auth/microsoft/callback

請務必複製用戶端密碼、重新導向 URI、租用戶 ID 和應用程式(用戶端)ID(在「概觀」下),因為稍後您會需要它們。

安裝相依性

npm install remix-auth-microsoft remix-auth

建立策略執行個體

// app/services/auth.server.ts
import { MicrosoftStrategy } from "remix-auth-microsoft";
import { Authenticator } from "remix-auth";

export let authenticator = new Authenticator<User>(); //User is a custom user types you can define as you want

let microsoftStrategy = new MicrosoftStrategy(
  {
    clientId: "YOUR_CLIENT_ID",
    clientSecret: "YOUR_CLIENT_SECRET",
    redirectURI: "https://example.com/auth/microsoft/callback",
    tenantId: "YOUR_TENANT_ID", // optional - necessary for organization without multitenant (see below)
    scopes: ["openid", "profile", "email"], // optional
    prompt: "login", // optional
  },
  async ({ request, tokens }) => {
    // Here you can fetch the user from database or return a user object based on profile
    let accessToken = tokens.accessToken();
    let idToken = tokens.idToken();
    let profile = await MicrosoftStrategy.userProfile(accessToken);

    // The returned object is stored in the session storage you are using by the authenticator

    // If you're using cookieSessionStorage, be aware that cookies have a size limit of 4kb

    // Retrieve or create user using id received from userinfo endpoint
    // https://graph.microsoft.com/oidc/userinfo

    // DO NOT USE EMAIL ADDRESS TO IDENTIFY USERS
    // The email address received from Microsoft Entra ID is not validated and can be changed to anything from Azure Portal.
    // If you use the email address to identify users and allow signing in from any tenant (`tenantId` is not set)
    // it opens up a possibility of spoofing users!

    return User.findOrCreate({ id: profile.id });
  }
);

authenticator.use(microsoftStrategy);

請參閱 Microsoft 文件,以取得有關 scopeprompt 參數的更多資訊。

具有單一租用戶驗證的應用程式(不允許使用多租用戶)

如果您只想允許來自單一組織的使用者登入,您應該將 tenantId 屬性新增至傳遞給 MicrosoftStrategy 的組態。tenantId 的值應該是您在應用程式註冊頁面的概觀下找到的目錄 (租用戶) ID

您也必須在應用程式註冊中選擇此組織目錄中的帳戶作為「支援的帳戶類型」。

後續步驟

請參閱 Remix Auth 文件,了解如何設定路由、在 Cookie 中保留會話等。