微软

启用 Microsoft Azure Entra ID(前称 Active Directory)的 OAuth 功能,允许用户使用他们的 Microsoft 账户登录和注册你的应用。

【Enabling OAuth with Microsoft Azure Entra ID (formerly Active Directory) allows your users to sign in and sign up to your application with their Microsoft account.】

获取你的微软凭证

要使用微软作为社交登录提供商,你需要获取你的微软凭证。这涉及使用你的 Microsoft Entra ID 仪表板账户生成你自己的客户端 ID 和客户端密钥。

请确保将重定向 URL 设置为 http://localhost:3000/api/auth/callback/microsoft,用于本地开发。对于生产环境,你应将其更改为你的应用的 URL。如果你更改了身份验证路由的基础路径,也应相应更新重定向 URL。

有关更多信息,请参阅 Microsoft Entra ID 文档

配置提供者

要配置提供者,你需要在认证配置中将 clientIdclientSecret 传递给 socialProviders.microsoft

auth.ts
import { betterAuth } from "better-auth"

export const auth = betterAuth({
    socialProviders: {
        microsoft: { 
            clientId: process.env.MICROSOFT_CLIENT_ID as string, 
            clientSecret: process.env.MICROSOFT_CLIENT_SECRET as string, 
            // Optional
            tenantId: 'common', 
            authority: "https://login.microsoftonline.com", // Authentication authority URL
            prompt: "select_account", // Forces account selection
        }, 
    },
})

权限 URL:对于标准 Entra ID 场景,请使用默认的 https://login.microsoftonline.com,对于 CIAM(客户身份与访问管理)场景,请使用 https://<tenant-id>.ciamlogin.com

使用 Microsoft 登录

【Sign In with Microsoft】

要使用 Microsoft 登录,你可以使用客户端提供的 signIn.social 函数。signIn 函数接收一个具有以下属性的对象:

【To sign in with Microsoft, you can use the signIn.social function provided by the client. The signIn function takes an object with the following properties:】

  • provider:要使用的提供者。它应设置为 microsoft
auth-client.ts
import { createAuthClient } from "better-auth/client";

const authClient = createAuthClient();

const signIn = async () => {
  const data = await authClient.signIn.social({
    provider: "microsoft",
    callbackURL: "/dashboard", // The URL to redirect to after the sign in
  });
};

On this page