Microsoft

启用 Microsoft Azure Entra ID(原 Active Directory)的 OAuth 功能可以让用户使用他们的 Microsoft 账户登录和注册你的应用程序。

获取 Microsoft 凭证

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

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

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

配置提供商

要配置提供商,你需要在 auth 配置中将 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, 
            // 可选配置
            tenantId: 'common', 
            requireSelectAccount: true
        }, 
    },
})

使用 Microsoft 登录

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

  • 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", // 登录后重定向的 URL
  });
};

On this page