Introduction
Hello everyone,
I am trying to implement azure active directory B2c into my nuxt 3 application. Because @nuxtjs/auth-next is not yet working for nuxt 3, I am trying to make my own composable that makes use of the @azure/msal-browser npm package.
The reason I am writing this article is because it is not working. The code I created can be seen below:
Error:
Terminal
[nitro] [dev] [unhandledRejection] BrowserAuthError: non_browser_environment: Login and token requests are not supported in non-browser environments. 21:07:32
at BrowserAuthError.AuthError [as constructor]
Browser console
PerformanceClient.ts:100 Uncaught (in promise) TypeError: this.startPerformanceMeasurement is not a function
at PerformanceClient2.startMeasurement
Code:
file: /composables/useAuth.js
import * as msal from '@azure/msal-browser'
let state = {
applicationInstance: null,
}
export const useAuth = () => {
//config auth
const msalConfig = {
auth: {
clientId: '',
authority: '',
knownAuthorities: [``],
redirectUri: '',
knownAuthorities: ['']
},
cache: {
cacheLocation: "sessionStorage", // This configures where your cache will be stored
storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
},
}
state.applicationInstance = new msal.PublicClientApplication(msalConfig);
return {
signIn
}
}
const signIn = () => {
//handle redirect
state.applicationInstance
.addEventCallback(event => {
if(event.type == "msal:loginSuccess" && event.payload.account)
{
const account = event.payload.account
state.applicationInstance.setActiveAccount(account)
console.log(account)
}
})
//handle auth redirect
state.applicationInstance
.handleRedirectPromise()
.then(() => {
const account = state.applicationInstance.getActiveAccount()
if(!account) {
const requestParams = {
scopes: ['openid', 'offline_access', 'User.Read'],
}
state.applicationInstance.loginRedirect(requestParams)
}
})
}
file: index.vue
<script setup>
const auth = useAuth();
auth.signIn()
</script>
CodePudding user response:
You need to make sure that you try to login only in the browser because Nuxt runs also server side.
You can check if you are client side with process.client
or process.server
for server side.
<script setup>
if (process.client) {
const auth = useAuth();
auth.signIn() // Try to sign in but only on client.
}
</script>
NuxtJS/VueJS: How to know if page was rendered on client-side only?