msal login implemented

This commit is contained in:
sumedh
2025-04-16 14:20:31 +05:30
parent 7e86fc7822
commit 5cc54c9332
6 changed files with 381 additions and 58 deletions

View File

@@ -2,24 +2,112 @@
import { useLayout } from '@/layout/composables/layout';
import { useAuth } from '@websanova/vue-auth/src/v3.js';
import Message from 'primevue/message';
import { computed, ref } from 'vue';
import { computed, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { msalInstance, state } from './MsalConfig';
import axios from 'axios';
const auth = useAuth();
const { isDarkTheme } = useLayout();
const username = ref('');
const password = ref('');
const error = ref('');
const visible = ref(false);
const router = useRouter();
const localState=state
const initialize = async () => {
try{
await msalInstance.initialize()
}catch(error){
console.log('Initialization error', error)
}
}
const loginWithCredentials = async () => {
try{
if (!msalInstance) {
throw new Error('MSAL not initialized. Call initialize() before using MSAL API.')
}
await msalInstance.loginRedirect()
localState.isAuthenticated = true
}catch (error) {
console.error('Login error:', error)
}
}
const logout = () => {
if (!msalInstance) {
throw new Error('MSAL not initialized. Call initialize() before using MSAL API.')
}
msalInstance.logoutRedirect()
localState.isAuthenticated = false
localState.user = null
}
const handleRedirect = async () => {
try {
const response = await msalInstance.handleRedirectPromise()
console.log("handleRedirectPromise result:", response)
const accounts = msalInstance.getAllAccounts()
console.log("Accounts after redirect:", accounts)
if (accounts.length > 0) {
localState.isAuthenticated = true
localState.user = accounts[0]
} else {
console.warn("No accounts found after redirect.")
}
} catch (error) {
console.error('Redirect error:', error)
}
}
const getToken = async () => {
if (!msalInstance) {
throw new Error('MSAL not initialized. Call initialize() before using MSAL API.')
}
try {
const accounts = msalInstance.getAllAccounts()
if (accounts.length === 0) {
throw new Error('No accounts found. Please login first.')
}
const silentRequest = {
scopes: ['api://d3fee0e3-49e0-4910-b0b4-805bfbd5488a/Po.Read'],
account: accounts[0]
}
const silentResponse = await msalInstance.acquireTokenSilent(silentRequest)
console.log('Silent token acquisition successful:', silentResponse)
return silentResponse.accessToken
} catch (error) {
console.error('Silent token acquisition error:', error)
}
}
const registerAuthorizationHeaderInterceptor = () => {
axios.interceptors.request.use(async (config) => {
const accessToken = await getToken()
if (accessToken) {
config.headers.Authorization = `Bearer ${accessToken}`
}
console.log('Request config:', config)
return config
})
}
// Optional: Auto-initialize or handle redirect on mount
onMounted(async () => {
await initialize()
await handleRedirect()
registerAuthorizationHeaderInterceptor()
const token = await getToken()
console.log("Access Token from manual fetch:", token)
})
const logoUrl = computed(() => {
return `/layout/images/${isDarkTheme ? 'logo-white' : 'logo-dark'}.svg`;
});
const login = async () => {
const login_old = async () => {
try {
await auth.login({
data:{
@@ -51,6 +139,7 @@ const login = async () => {
}
}
</script>
<template>
@@ -96,8 +185,8 @@ const login = async () => {
<a class="font-medium no-underline ml-2 text-right cursor-pointer" style="color: var(--primary-color)">Forgot password?</a>
</div>
-->
<Button @click="login" label="Sign In" class="w-full p-4 text-xl"></Button>
<Button @click="login_old" label="Sign In with Username & Password" class="w-full p-4 text-xl mb-4" />
<Button @click="loginWithCredentials" label="Sign In with Microsoft" class="w-full p-4 text-xl" />
<Message v-if="visible" severity="error" :life="3000" class="mt-2 error-message">{{ error }}</Message>
</div>
</div>

View File

@@ -0,0 +1,26 @@
import { PublicClientApplication } from '@azure/msal-browser';
import { reactive } from 'vue';
export const msalConfig = {
auth: {
clientId: 'd3fee0e3-49e0-4910-b0b4-805bfbd5488a',
authority: 'https://login.microsoftonline.com/9dc4721e-4d54-4c40-a681-1dd740292901',
redirectUri: 'http://localhost:5173/temp',
postLogoutUri: 'http://localhost:5173'
},
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: false
}
};
export const graphScopes = {
scopes: ['user.read', 'openid', 'profile']
};
export const state = reactive({
isAuthenticated: false,
user: null
});
export const msalInstance = new PublicClientApplication(msalConfig);

View File

@@ -0,0 +1,11 @@
<!-- src/components/TestPage.vue -->
<template>
<div>
<h1>Test Page</h1>
<p>You are successfully logged in!</p>
</div>
</template>
<script setup>
// No need for `export default` here with the `<script setup>` syntax.
</script>