Autentica mediante SAML en apps web
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Si actualizaste a Firebase Authentication with Identity Platform, puedes autenticar a tus usuarios con Firebase
mediante el proveedor de identidad de SAML que prefieras. Esto permite usar
la solución de SSO basada en SAML para que los usuarios accedan a la app de Firebase.
Firebase Authentication solo admite el flujo de SAML iniciado por el proveedor de servicios.
Antes de comenzar
Para que los usuarios accedan mediante un proveedor de identidad de SAML, primero debes recopilar cierta
información del proveedor:
- ID de entidad del proveedor: Es un URI que identifica al proveedor de identidad.
- URL de SSO de SAML del proveedor: Es la URL de la página de acceso del proveedor de
identidad.
- Certificado de clave pública del proveedor: Es el certificado que se usa para validar
los tokens firmados por el proveedor de identidad.
- ID de entidad de tu app: Es un URI que identifica a tu app, el “proveedor
de servicios”.
Una vez que tengas la información anterior, habilita SAML como proveedor de acceso para el
proyecto de Firebase.
Agrega Firebase a tu proyecto de JavaScript.
Si aún no lo hiciste, actualiza a Firebase Authentication with Identity Platform. La autenticación de SAML solo está
disponible en proyectos actualizados.
En la página Proveedores de acceso
de Firebase console, haz clic en Agregar proveedor nuevo y, luego, en
SAML.
Asígnale un nombre a este proveedor. Toma nota del ID de proveedor que se genera
(algo como saml.example-provider
). Lo necesitarás cuando agregues
el código de acceso a tu app.
Especifica el ID de entidad del proveedor de identidad, la URL de SSO y el certificado de clave
pública. También especifica el ID de entidad de tu app (el proveedor de servicios).
Estos valores deben coincidir exactamente con los valores que te asignó el proveedor.
Guarda los cambios.
Si aún no autorizas el dominio de tu app, agrégalo a la lista de entidades permitidas
en la página Autenticación > Configuración
de Firebase console.
Maneja el flujo de acceso con el SDK de Firebase
Para manejar el flujo de acceso con el SDK de Firebase JavaScript,
sigue estos pasos:
Crea una instancia de un SAMLAuthProvider
con el ID de proveedor que obtuviste en
Firebase console.
Web
import { SAMLAuthProvider } from "firebase/auth";
const provider = new SAMLAuthProvider('saml.example-provider');
Web
var provider = new firebase.auth.SAMLAuthProvider('saml.example-provider');
``
Autentica con Firebase mediante el objeto del proveedor de SAML.
Puedes redireccionar al usuario a la página de acceso del proveedor o abrir la
página de acceso en una ventana emergente del navegador.
Flujo de redireccionamiento
Para redireccionar a la página de acceso del proveedor, llama a signInWithRedirect()
:
Web
import { getAuth, signInWithRedirect } from "firebase/auth";
const auth = getAuth();
signInWithRedirect(auth, provider);
Web
firebase.auth().signInWithRedirect(provider);
Después de que el usuario termine de acceder y vuelva a tu app, puedes obtener el
resultado de acceso con solo llamar a getRedirectResult()
.
Web
import { getAuth, getRedirectResult, SAMLAuthProvider } from "firebase/auth";
const auth = getAuth();
getRedirectResult(auth)
.then((result) => {
// User is signed in.
// Provider data available using getAdditionalUserInfo()
})
.catch((error) => {
// Handle error.
});
Web
firebase.auth().getRedirectResult()
.then((result) => {
// User is signed in.
// Provider data available in result.additionalUserInfo.profile,
// or from the user's ID token obtained from result.user.getIdToken()
// as an object in the firebase.sign_in_attributes custom claim.
})
.catch((error) => {
// Handle error.
});
Flujo de ventana emergente
Web
import { getAuth, signInWithPopup, OAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// User is signed in.
// Provider data available in result.additionalUserInfo.profile,
// or from the user's ID token obtained from result.user.getIdToken()
// as an object in the firebase.sign_in_attributes custom claim.
})
.catch((error) => {
// Handle error.
});
Web
firebase.auth().signInWithPopup(provider)
.then((result) => {
// User is signed in.
// Provider data available in result.additionalUserInfo.profile,
// or from the user's ID token obtained from result.user.getIdToken()
// as an object in the firebase.sign_in_attributes custom claim.
})
.catch((error) => {
// Handle error.
});
El token de ID y el objeto UserInfo contienen la dirección de correo electrónico del usuario solo si se proporciona en el atributo NameID
de la aserción de SAML del proveedor de identidad:
<Subject>
<NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">test@email.com</NameID>
</Subject>
Si bien los ejemplos anteriores se enfocan en los flujos de acceso, puedes usar el mismo
patrón para vincular un proveedor de SAML con un usuario existente mediante
linkWithRedirect()
y linkWithPopup()
, y volver a autenticar a un usuario con
reauthenticateWithRedirect()
y reauthenticateWithPopup()
, que se pueden
usar para recuperar credenciales nuevas para operaciones sensibles que requieren
un acceso reciente.
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-08-08 (UTC)
[null,null,["Última actualización: 2025-08-08 (UTC)"],[],[],null,["If you've upgraded to Firebase Authentication with Identity Platform, you can authenticate your users with Firebase\nusing the SAML identity provider of your choice. This makes it possible to use\nyour SAML-based SSO solution to sign users in to your Firebase app.\n\nFirebase Authentication supports only the service-provider initiated SAML flow.\n\nBefore you begin\n\nTo sign in users using a SAML identity provider, you must first collect some\ninformation from the provider:\n\n- **The provider's Entity ID**: A URI that identifies the identity provider.\n- **The provider's SAML SSO URL**: The URL of the identity provider's sign-in page.\n- **The provider's public key certificate**: The certificate used to validate tokens signed by the identity provider.\n- **Your app's Entity ID**: A URI that identifies your app, the \"service provider\".\n\nAfter you have the above information, enable SAML as a sign-in provider for your\nFirebase project:\n\n1. [Add Firebase to your JavaScript project](/docs/web/setup).\n\n2. If you haven't upgraded to Firebase Authentication with Identity Platform, do so. SAML authentication is only\n available in upgraded projects.\n\n3. On the [**Sign-in providers**](//console.firebase.google.com/project/_/authentication/providers)\n page of the Firebase console, click **Add new provider** , and then click\n **SAML**.\n\n4. Give a name to this provider. Note the provider ID that's generated:\n something like `saml.example-provider`. You'll need this ID when you add\n sign-in code to your app.\n\n5. Specify your identity provider's entity ID, SSO URL, and public key\n certificate. Also specify the entity ID of your app (the service provider).\n These values must exactly match the values your provider assigned to you.\n\n6. Save your changes.\n\n7. If you haven't already authorized your app's domain, add it to the allow\n list on the [**Authentication \\\u003e Settings**](//console.firebase.google.com/project/_/authentication/settings)\n page of the Firebase console.\n\nHandle the sign-in flow with the Firebase SDK\n\nTo handle the sign-in flow with the Firebase JavaScript SDK, follow these\nsteps:\n\n1. Create an instance of an `SAMLAuthProvider` using the provider ID you got in\n the Firebase console.\n\n Web \n\n import { SAMLAuthProvider } from \"firebase/auth\";\n\n const provider = new SAMLAuthProvider('saml.example-provider');\n\n Web \n\n var provider = new firebase.auth.SAMLAuthProvider('saml.example-provider');\n ``\n\n\u003c!-- --\u003e\n\n1. Authenticate with Firebase using the SAML provider object.\n\n You can either redirect the user to the provider's sign-in page or open the\n sign-in page in a pop-up browser window.\n\n **Redirect flow**\n\n Redirect to the provider sign-in page by calling `signInWithRedirect()`: \n\n Web \n\n import { getAuth, signInWithRedirect } from \"firebase/auth\";\n\n const auth = getAuth();\n signInWithRedirect(auth, provider);\n\n Web \n\n firebase.auth().signInWithRedirect(provider);\n\n After the user completes sign-in and returns to your app, you can obtain the\n sign-in result by calling `getRedirectResult()`. \n\n Web \n\n import { getAuth, getRedirectResult, SAMLAuthProvider } from \"firebase/auth\";\n\n const auth = getAuth();\n getRedirectResult(auth)\n .then((result) =\u003e {\n // User is signed in.\n\n // Provider data available using getAdditionalUserInfo()\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n Web \n\n firebase.auth().getRedirectResult()\n .then((result) =\u003e {\n // User is signed in.\n\n // Provider data available in result.additionalUserInfo.profile,\n // or from the user's ID token obtained from result.user.getIdToken()\n // as an object in the firebase.sign_in_attributes custom claim.\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n **Pop-up flow**\n\n Web \n\n import { getAuth, signInWithPopup, OAuthProvider } from \"firebase/auth\";\n\n const auth = getAuth();\n signInWithPopup(auth, provider)\n .then((result) =\u003e {\n // User is signed in.\n\n // Provider data available in result.additionalUserInfo.profile,\n // or from the user's ID token obtained from result.user.getIdToken()\n // as an object in the firebase.sign_in_attributes custom claim.\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n Web \n\n firebase.auth().signInWithPopup(provider)\n .then((result) =\u003e {\n // User is signed in.\n\n // Provider data available in result.additionalUserInfo.profile,\n // or from the user's ID token obtained from result.user.getIdToken()\n // as an object in the firebase.sign_in_attributes custom claim.\n })\n .catch((error) =\u003e {\n // Handle error.\n });\n\n The ID token and [UserInfo](/docs/reference/js/auth.userinfo#userinfoemail)\n object contains the user's email address only if it is provided in the\n `NameID` attribute of the SAML assertion from the identity provider: \n\n \u003cSubject\u003e\n \u003cNameID Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress\"\u003etest@email.com\u003c/NameID\u003e\n \u003c/Subject\u003e\n\n2. While the above examples focus on sign-in flows, you can use the same\n pattern to link a SAML provider to an existing user using\n `linkWithRedirect()` and `linkWithPopup()`, and re-authenticate a user with\n `reauthenticateWithRedirect()` and `reauthenticateWithPopup()`, which can be\n used to retrieve fresh credentials for sensitive operations that require\n recent login."]]