В настоящее время я работаю над приложением React, где я изначально использовал SessionStorage для хранения данных сеанса пользователя. Тем не менее, мне нужно переключиться на LocalStorage, потому что у меня есть несколько ссылок, которые открываются на новой вкладке (тот же веб -сайт), и использование SessionStorage требует, чтобы пользователь снова входил в систему на новой вкладке. < /P>
Вот изменение, которое я сделал: < /p>
cachelocation: "localstorage", < /p>
< /blockquote>
SessionStorage работал нормально после перехода на LocalStorage, я столкнулся с проблемой, где после успешного входа (подтверждено через журналы консоли), я сразу же подписал. Или может предоставить руководство по поводу того, что может вызвать эту проблему? Любая помощь будет очень признателен! > Используется для настройки моих настроек < /p>
import { LogLevel } from "@azure/msal-browser";
/**
* Configuration object for MSAL (Microsoft Authentication Library).
* This object is used to initialize the MSAL instance with the necessary settings.
*/
export const msalConfig = {
/**
* Authentication parameters.
*/
auth: {
/**
* The client ID of your application. This is a mandatory field.
* @example "xxxxxxx"
*/
clientId: "xxxxxxx",
/**
* The authority URL for your tenant. Replace the placeholder with your tenant subdomain.
* @example "https://xxxxx.ciamlogin.com/"
*/
authority: "https://xxxxx.ciamlogin.com/",
/**
* The redirect URI after a successful login. This should be registered in the Microsoft Entra admin center/App Registration.
* @example "https://xxxxx.xxxxx.com/"
*/
redirectUri: "http://xxxxx:xxxxx/",
/**
* The URI to navigate to after logout.
* @example "/"
*/
postLogoutRedirectUri: "/",
/**
* If true, will navigate back to the original request location before processing the auth code response.
* @default false
*/
navigateToLoginRequestUrl: true,
},
/**
* Cache configuration parameters.
*/
cache: {
/**
* Specifies where the cache should be stored. Options are "localStorage" or "sessionStorage".
* @default "sessionStorage"
*/
cacheLocation: "localStorage",
/**
* If true, the authentication state will be stored in cookies.
* @default false
*/
storeAuthStateInCookie: false,
},
/**
* System configuration parameters.
*/
system: {
/**
* Logger options for MSAL.
*/
loggerOptions: {
/**
* Callback function for logging messages.
* @param level - The log level (Error, Info, Verbose, Warning).
* @param message - The log message.
* @param containsPii - Indicates if the message contains Personally Identifiable Information (PII).
*/
loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
},
},
},
};
export const accessTokenRequest = {
scopes: ["api://xxxx-xxxxx/xxxx"],
};
export const loginRequest = {
scopes: ["User.Read"],
};
< /code>
authprovider.tsx> используется для проверки входа в систему и установки активной учетной записи. < /p>
import { AuthenticationResult, EventType, PublicClientApplication } from "@azure/msal-browser";
import { msalConfig } from "./authConfig";
import { ReactNode } from "react";
import { MsalProvider } from "@azure/msal-react";
interface AuthProviderProps {
children: ReactNode;
}
export const AuthProvider = ({ children }: AuthProviderProps) => {
const msalInstance = new PublicClientApplication(msalConfig);
msalInstance.addEventCallback((event) => {
const authenticationResult = event.payload as AuthenticationResult;
const account = authenticationResult?.account;
if (event.eventType === EventType.LOGIN_SUCCESS && account) {
msalInstance.setActiveAccount(account);
}
});
return {children};
};
main.tsx
import ReactDOM from "react-dom/client";
import App from "./App";
import { AuthProvider } from "./services/authProvider";
ReactDOM.createRoot(document.getElementById("root")!).render(
);
app.tsx
import { lazy, Suspense, useEffect } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./tailwind.css";
import { themeChange } from "./scripts/ThemeMode.tsx";
import { AuthenticatedTemplate, UnauthenticatedTemplate } from "@azure/msal-react";
const About = lazy(() => import("./pages/About.tsx"));
const Login = lazy(() => import("./pages/Login.tsx"));
function App() {
useEffect(() => {
themeChange();
}, []);
return (
);
}
export default App;
Подробнее здесь: https://stackoverflow.com/questions/794 ... gin-system
React MSAL SessionStorage на систему локального входа ⇐ Javascript
Форум по Javascript
-
Anonymous
1738934751
Anonymous
В настоящее время я работаю над приложением React, где я изначально использовал SessionStorage для хранения данных сеанса пользователя. Тем не менее, мне нужно переключиться на LocalStorage, потому что у меня есть несколько ссылок, которые открываются на новой вкладке (тот же веб -сайт), и использование SessionStorage требует, чтобы пользователь снова входил в систему на новой вкладке. < /P>
Вот изменение, которое я сделал: < /p>
cachelocation: "localstorage", < /p>
< /blockquote>
SessionStorage работал нормально после перехода на LocalStorage, я столкнулся с проблемой, где после успешного входа (подтверждено через журналы консоли), я сразу же подписал. Или может предоставить руководство по поводу того, что может вызвать эту проблему? Любая помощь будет очень признателен! > Используется для настройки моих настроек < /p>
import { LogLevel } from "@azure/msal-browser";
/**
* Configuration object for MSAL (Microsoft Authentication Library).
* This object is used to initialize the MSAL instance with the necessary settings.
*/
export const msalConfig = {
/**
* Authentication parameters.
*/
auth: {
/**
* The client ID of your application. This is a mandatory field.
* @example "xxxxxxx"
*/
clientId: "xxxxxxx",
/**
* The authority URL for your tenant. Replace the placeholder with your tenant subdomain.
* @example "https://xxxxx.ciamlogin.com/"
*/
authority: "https://xxxxx.ciamlogin.com/",
/**
* The redirect URI after a successful login. This should be registered in the Microsoft Entra admin center/App Registration.
* @example "https://xxxxx.xxxxx.com/"
*/
redirectUri: "http://xxxxx:xxxxx/",
/**
* The URI to navigate to after logout.
* @example "/"
*/
postLogoutRedirectUri: "/",
/**
* If true, will navigate back to the original request location before processing the auth code response.
* @default false
*/
navigateToLoginRequestUrl: true,
},
/**
* Cache configuration parameters.
*/
cache: {
/**
* Specifies where the cache should be stored. Options are "localStorage" or "sessionStorage".
* @default "sessionStorage"
*/
cacheLocation: "localStorage",
/**
* If true, the authentication state will be stored in cookies.
* @default false
*/
storeAuthStateInCookie: false,
},
/**
* System configuration parameters.
*/
system: {
/**
* Logger options for MSAL.
*/
loggerOptions: {
/**
* Callback function for logging messages.
* @param level - The log level (Error, Info, Verbose, Warning).
* @param message - The log message.
* @param containsPii - Indicates if the message contains Personally Identifiable Information (PII).
*/
loggerCallback: (level: LogLevel, message: string, containsPii: boolean) => {
if (containsPii) {
return;
}
switch (level) {
case LogLevel.Error:
console.error(message);
return;
case LogLevel.Info:
console.info(message);
return;
case LogLevel.Verbose:
console.debug(message);
return;
case LogLevel.Warning:
console.warn(message);
return;
}
},
},
},
};
export const accessTokenRequest = {
scopes: ["api://xxxx-xxxxx/xxxx"],
};
export const loginRequest = {
scopes: ["User.Read"],
};
< /code>
[b] authprovider.tsx[/b]> используется для проверки входа в систему и установки активной учетной записи. < /p>
import { AuthenticationResult, EventType, PublicClientApplication } from "@azure/msal-browser";
import { msalConfig } from "./authConfig";
import { ReactNode } from "react";
import { MsalProvider } from "@azure/msal-react";
interface AuthProviderProps {
children: ReactNode;
}
export const AuthProvider = ({ children }: AuthProviderProps) => {
const msalInstance = new PublicClientApplication(msalConfig);
msalInstance.addEventCallback((event) => {
const authenticationResult = event.payload as AuthenticationResult;
const account = authenticationResult?.account;
if (event.eventType === EventType.LOGIN_SUCCESS && account) {
msalInstance.setActiveAccount(account);
}
});
return {children};
};
[b] main.tsx[/b]
import ReactDOM from "react-dom/client";
import App from "./App";
import { AuthProvider } from "./services/authProvider";
ReactDOM.createRoot(document.getElementById("root")!).render(
);
[b] app.tsx[/b]
import { lazy, Suspense, useEffect } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import "./tailwind.css";
import { themeChange } from "./scripts/ThemeMode.tsx";
import { AuthenticatedTemplate, UnauthenticatedTemplate } from "@azure/msal-react";
const About = lazy(() => import("./pages/About.tsx"));
const Login = lazy(() => import("./pages/Login.tsx"));
function App() {
useEffect(() => {
themeChange();
}, []);
return (
);
}
export default App;
Подробнее здесь: [url]https://stackoverflow.com/questions/79421042/react-msal-sessionstorage-to-localstorage-login-system[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия