msal working
This commit is contained in:
@@ -57,7 +57,7 @@ var auth = createAuth({
|
||||
}
|
||||
});
|
||||
|
||||
axios.defaults.baseURL = import.meta.env.VITE_BACKEND_URL;//'http://localhost:8081'///
|
||||
axios.defaults.baseURL = 'http://localhost:8899'///
|
||||
//axios.defaults.baseURL ='http://localhost:8081';
|
||||
|
||||
|
||||
|
||||
@@ -63,12 +63,18 @@ const router = createRouter({
|
||||
{
|
||||
path: '/auth/login',
|
||||
name: 'login',
|
||||
meta: {
|
||||
auth: false
|
||||
},
|
||||
component: () => import('@/views/pages/auth/Login.vue')
|
||||
},
|
||||
{
|
||||
path: '/temp',
|
||||
path: '/auth/callback',
|
||||
name: 'test',
|
||||
component: () => import('@/views/pages/auth/Temp.vue')
|
||||
meta: {
|
||||
auth: false
|
||||
},
|
||||
component: () => import('@/views/pages/auth/Callback.vue')
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
56
src/views/pages/auth/Callback.vue
Normal file
56
src/views/pages/auth/Callback.vue
Normal file
@@ -0,0 +1,56 @@
|
||||
<script setup>
|
||||
import { useAuth } from '@websanova/vue-auth/src/v3.js';
|
||||
import axios from 'axios';
|
||||
import { onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { msalInstance } from './MsalConfig'; // wherever you created your MSAL instance
|
||||
|
||||
const router = useRouter()
|
||||
const auth = useAuth();
|
||||
|
||||
onMounted(async () => {
|
||||
console.log("Mounted on callback")
|
||||
|
||||
await msalInstance.initialize()
|
||||
console.log("After initialize on callback")
|
||||
|
||||
const response = await msalInstance.handleRedirectPromise()
|
||||
|
||||
console.log("Response:",response)
|
||||
|
||||
if (response) {
|
||||
// Do something with the response, e.g. save the user
|
||||
localStorage.setItem('msalUser', JSON.stringify(response.account))
|
||||
axios.post("/msauth/exchange",{}, {
|
||||
headers: { Authorization: `Bearer ${response.accessToken}` }
|
||||
}).then(res=>{
|
||||
if(res.data.token){
|
||||
auth.token(null,res.data.token,false);
|
||||
auth.fetch().then(response=>{
|
||||
console.log("1 user :" , response.data.data);
|
||||
|
||||
if (!response.data.data.selectedProject) {
|
||||
router.push({ name: 'projects-list' });
|
||||
} else {
|
||||
router.push({ name: 'scenario-list' });
|
||||
}
|
||||
|
||||
})
|
||||
}else{
|
||||
console.error("No token exchange with backend")
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>Redirecting...</div>
|
||||
</template>
|
||||
@@ -1,12 +1,11 @@
|
||||
<script setup>
|
||||
import { useLayout } from '@/layout/composables/layout';
|
||||
import { useAuth } from '@websanova/vue-auth/src/v3.js';
|
||||
import Message from 'primevue/message';
|
||||
import { computed, ref, onMounted } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { msalInstance, state } from './MsalConfig';
|
||||
import axios from 'axios';
|
||||
|
||||
import Message from 'primevue/message';
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { msalInstance } from './MsalConfig';
|
||||
const auth = useAuth();
|
||||
const { isDarkTheme } = useLayout();
|
||||
const username = ref('');
|
||||
@@ -14,98 +13,54 @@ 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
|
||||
const msaccount = ref(null);
|
||||
onMounted(async () => {
|
||||
await initialize()
|
||||
await handleRedirect()
|
||||
registerAuthorizationHeaderInterceptor()
|
||||
const token = await getToken()
|
||||
console.log("Access Token from manual fetch:", token)
|
||||
await msalInstance.initialize()
|
||||
const accounts = msalInstance.getAllAccounts()
|
||||
|
||||
console.log("Accounts:",accounts)
|
||||
if (accounts.length > 0) {
|
||||
console.log(accounts)
|
||||
msaccount.value= accounts[0]
|
||||
|
||||
}
|
||||
})
|
||||
|
||||
const logoUrl = computed(() => {
|
||||
return `/layout/images/${isDarkTheme ? 'logo-white' : 'logo-dark'}.svg`;
|
||||
});
|
||||
const loginAD = async () => {
|
||||
|
||||
var token = await msalInstance.acquireTokenSilent({
|
||||
scopes: ["api://d3fee0e3-49e0-4910-b0b4-805bfbd5488a/access_as_user"],
|
||||
account: msaccount.value
|
||||
})
|
||||
console.log("Token " ,token)
|
||||
|
||||
axios.post("/msauth/exchange",{}, {
|
||||
headers: { Authorization: `Bearer ${token.accessToken}` }
|
||||
}).then(res=>{
|
||||
console.log("Token exhange done :",res.data.token)
|
||||
if(res.data.token){
|
||||
auth.token(null, res.data.token,false)
|
||||
auth.fetch().then(response=>{
|
||||
console.log("1 user :" , response.data.data);
|
||||
|
||||
if (!response.data.data.selectedProject) {
|
||||
router.push({ name: 'projects-list' });
|
||||
} else {
|
||||
router.push({ name: 'scenario-list' });
|
||||
}
|
||||
})
|
||||
}else{
|
||||
console.error("No token exchange with backend")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const loginMsal = async () => {
|
||||
await msalInstance.initialize()
|
||||
msalInstance.loginRedirect({
|
||||
scopes: ["api://d3fee0e3-49e0-4910-b0b4-805bfbd5488a/access_as_user"]
|
||||
})
|
||||
}
|
||||
|
||||
const login_old = async () => {
|
||||
try {
|
||||
@@ -186,7 +141,8 @@ const login_old = async () => {
|
||||
</div>
|
||||
-->
|
||||
<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" />
|
||||
<Button @click="loginMsal" v-if="msaccount == null" label="Sign In with Microsoft" class="w-full p-4 text-xl" />
|
||||
<Button @click="loginAD" v-if="msaccount" :label="'Login ' + msaccount.username " class="w-full p-4 text-xl" />
|
||||
<Message v-if="visible" severity="error" :life="3000" class="mt-2 error-message">{{ error }}</Message>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,26 +1,19 @@
|
||||
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);
|
||||
export const msalInstance = new PublicClientApplication({
|
||||
auth: {
|
||||
clientId: 'd3fee0e3-49e0-4910-b0b4-805bfbd5488a',
|
||||
authority: "https://login.microsoftonline.com/9dc4721e-4d54-4c40-a681-1dd740292901",
|
||||
redirectUri: "http://localhost:5173/auth/callback", // or your deployed URL
|
||||
navigateToLoginRequestUrl: false,
|
||||
},
|
||||
cache: {
|
||||
cacheLocation: "localStorage",
|
||||
storeAuthStateInCookie: false,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
<!-- 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>
|
||||
Reference in New Issue
Block a user