How do I display Job Title in my Next Auth app
Asked Answered
T

1

1

How do I display Job Title and other user properties in my Next Auth app using Azure AD / Entra ID.

I am using next-auth v5 and Next.js V14 so I have an app directory and no pages directory.

This is my route.tsx (placed in [...nextauth]/):

import NextAuth from "next-auth";
import { options } from "./options";

export const {
    handlers: { GET, POST },
    auth,
    signIn,
    signOut,
  } = NextAuth(options);

this is my options.tsx:

import type { NextAuthOptions } from "next-auth";
import AzureADProvider from "next-auth/providers/azure-ad";

export const options: NextAuthOptions = {
    providers: [
        AzureADProvider({
            clientId: process.env.AZURE_AD_CLIENT_ID,
            clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
            tenantId: process.env.AZURE_AD_TENANT_ID,
        }),
    ],
}

and this is my page.tsx:

import { auth, signOut } from "./api/auth/[...nextauth]/route"

function SignOut() {
  return (
    <form action={async () => {
      'use server';
      await signOut()
    }}>
      <button type="submit">Sign out</button>
    </form>
  )
}

export default async function Home() {
  const session = await auth();
  return (
    <>
      {session?.user ? (
        <div>
          <p>Welcome {session.user.name}!</p>
          <div><SignOut /></div>
        </div>
      ) : (
        <div>
          <p>You are signed out!</p>
          <a href="/api/auth/signin"><button>Sign in</button></a>
        </div>
      )}
    </>
  );
}

Please help me. Thanks in advance!

Transarctic answered 14/6, 2024 at 15:0 Comment(15)
To display the job title make use of GET https://graph.microsoft.com/v1.0/users/UserID?$select=jobTitle queryHibbler
@Rukmini, but how do I use it in my code. And I only want currently logged in user's jobTitleTransarctic
For logged in user job title make use of GET https://graph.microsoft.com/v1.0/me?$select=jobTitle queryHibbler
Does your code generate access token?Hibbler
I think so but I am not sure, I created a new project and the only files I changed are the three files I mentioned in question.Transarctic
Hi @Rukmini, I checked it, couldn't find anything related to displaying user's information. Besides they are using next v13. I don't have a pages directoryTransarctic
Check this github.com/dwarfered/ms-identity-nextjs-sampleHibbler
The above Github exactly is what you need let me know if it worksHibbler
Hi @Rukmini, I think it works, but they are not using next-auth libraryTransarctic
My org is currently using next-auth, I have to check if I can avoid using it and follow this method instead. But you have contributed a lot of your time and efforts into this and I thank you very much for it.Transarctic
I got the output successfully when I ran the codeHibbler
I asked, they said we need to use next-auth 😔Transarctic
Sure will check with next-authHibbler
Hi @rukmini, any luck?Transarctic
Let us continue this discussion in chat.Hibbler
F
1

This works

In your options.tsx add this:

providers: [
    AzureADProvider({
      clientId: process.env.AZURE_AD_CLIENT_ID,
      clientSecret: process.env.AZURE_AD_CLIENT_SECRET,
      tenantId: process.env.AZURE_AD_TENANT_ID,
    })
  ],
  callbacks: {
    jwt({ token, account }) {
      if (account){
        token.accessToken = account.access_token;
      }
      return token;
    },
    async session({ session, token }) {
      if (token.accessToken) {
        try {
          const response = await axios.get('https://graph.microsoft.com/v1.0/me?$select=jobTitle', {
            headers: {
              Authorization: `Bearer ${token.accessToken}`,
            },
          });
          session.user.jobTitle = response.data.jobTitle;
        } catch (error) {
          console.error('Error fetching job title from Microsoft Graph API:', error);
        }
      }
      return session;
    },
  }

now you can use in your script as session.user.jobTitle

Fidge answered 20/6, 2024 at 4:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.