सत्र कुकीज़ प्रबंधित करें

फायरबेस ऑथ उन पारंपरिक वेबसाइटों के लिए सर्वर-साइड सत्र कुकी प्रबंधन प्रदान करता है जो सत्र कुकीज़ पर निर्भर हैं। क्लाइंट-साइड अल्पकालिक आईडी टोकन पर इस समाधान के कई फायदे हैं, जिन्हें समाप्ति पर सत्र कुकी को अपडेट करने के लिए हर बार रीडायरेक्ट तंत्र की आवश्यकता हो सकती है:

  • JWT-आधारित सत्र टोकन के माध्यम से बेहतर सुरक्षा जो केवल अधिकृत सेवा खातों का उपयोग करके उत्पन्न की जा सकती है।
  • स्टेटलेस सत्र कुकीज़ जो प्रमाणीकरण के लिए जेडब्ल्यूटी का उपयोग करने के सभी लाभों के साथ आती हैं। सत्र कुकी में आईडी टोकन के समान दावे (कस्टम दावों सहित) हैं, जो सत्र कुकीज़ पर समान अनुमतियों की जांच को लागू करने योग्य बनाते हैं।
  • 5 मिनट से लेकर 2 सप्ताह तक की कस्टम समाप्ति समय के साथ सत्र कुकीज़ बनाने की क्षमता।
  • एप्लिकेशन आवश्यकताओं के आधार पर कुकी नीतियों को लागू करने का लचीलापन: डोमेन, पथ, सुरक्षित, httpOnly , आदि।
  • मौजूदा ताज़ा टोकन निरस्तीकरण एपीआई का उपयोग करके टोकन चोरी का संदेह होने पर सत्र कुकीज़ को रद्द करने की क्षमता।
  • प्रमुख खाता परिवर्तनों पर सत्र निरस्तीकरण का पता लगाने की क्षमता।

दाखिल करना

यह मानते हुए कि कोई एप्लिकेशन httpOnly सर्वर साइड कुकीज़ का उपयोग कर रहा है, क्लाइंट SDK का उपयोग करके लॉगिन पेज पर उपयोगकर्ता को साइन इन करें। एक फायरबेस आईडी टोकन उत्पन्न होता है, और आईडी टोकन को HTTP POST के माध्यम से एक सत्र लॉगिन एंडपॉइंट पर भेजा जाता है, जहां एडमिन एसडीके का उपयोग करके, एक सत्र कुकी उत्पन्न होती है। सफलता पर, राज्य को क्लाइंट साइड स्टोरेज से साफ़ किया जाना चाहिए।

firebase.initializeApp({
  apiKey: 'AIza…',
  authDomain: '<PROJECT_ID>.firebasepp.com'
});

// As httpOnly cookies are to be used, do not persist any state client side.
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);

// When the user signs in with email and password.
firebase.auth().signInWithEmailAndPassword('user@example.com', 'password').then(user => {
  // Get the user's ID token as it is needed to exchange for a session cookie.
  return user.getIdToken().then(idToken = > {
    // Session login endpoint is queried and the session cookie is set.
    // CSRF protection should be taken into account.
    // ...
    const csrfToken = getCookie('csrfToken')
    return postIdTokenToSessionLogin('/sessionLogin', idToken, csrfToken);
  });
}).then(() => {
  // A page redirect would suffice as the persistence is set to NONE.
  return firebase.auth().signOut();
}).then(() => {
  window.location.assign('/profile');
});

प्रदत्त आईडी टोकन के बदले में एक सत्र कुकी उत्पन्न करने के लिए, एक HTTP समापन बिंदु की आवश्यकता होती है। फायरबेस एडमिन एसडीके का उपयोग करके एक कस्टम सत्र अवधि समय निर्धारित करते हुए, टोकन को अंतिम बिंदु पर भेजें। क्रॉस-साइट अनुरोध जालसाजी (सीएसआरएफ) हमलों को रोकने के लिए उचित उपाय किए जाने चाहिए।

नोड.जे.एस

app.post('/sessionLogin', (req, res) => {
  // Get the ID token passed and the CSRF token.
  const idToken = req.body.idToken.toString();
  const csrfToken = req.body.csrfToken.toString();
  // Guard against CSRF attacks.
  if (csrfToken !== req.cookies.csrfToken) {
    res.status(401).send('UNAUTHORIZED REQUEST!');
    return;
  }
  // Set session expiration to 5 days.
  const expiresIn = 60 * 60 * 24 * 5 * 1000;
  // Create the session cookie. This will also verify the ID token in the process.
  // The session cookie will have the same claims as the ID token.
  // To only allow session cookie setting on recent sign-in, auth_time in ID token
  // can be checked to ensure user was recently signed in before creating a session cookie.
  getAuth()
    .createSessionCookie(idToken, { expiresIn })
    .then(
      (sessionCookie) => {
        // Set cookie policy for session cookie.
        const options = { maxAge: expiresIn, httpOnly: true, secure: true };
        res.cookie('session', sessionCookie, options);
        res.end(JSON.stringify({ status: 'success' }));
      },
      (error) => {
        res.status(401).send('UNAUTHORIZED REQUEST!');
      }
    );
});

जावा

@POST
@Path("/sessionLogin")
@Consumes("application/json")
public Response createSessionCookie(LoginRequest request) {
  // Get the ID token sent by the client
  String idToken = request.getIdToken();
  // Set session expiration to 5 days.
  long expiresIn = TimeUnit.DAYS.toMillis(5);
  SessionCookieOptions options = SessionCookieOptions.builder()
      .setExpiresIn(expiresIn)
      .build();
  try {
    // Create the session cookie. This will also verify the ID token in the process.
    // The session cookie will have the same claims as the ID token.
    String sessionCookie = FirebaseAuth.getInstance().createSessionCookie(idToken, options);
    // Set cookie policy parameters as required.
    NewCookie cookie = new NewCookie("session", sessionCookie /* ... other parameters */);
    return Response.ok().cookie(cookie).build();
  } catch (FirebaseAuthException e) {
    return Response.status(Status.UNAUTHORIZED).entity("Failed to create a session cookie")
        .build();
  }
}

अजगर

@app.route('/sessionLogin', methods=['POST'])
def session_login():
    # Get the ID token sent by the client
    id_token = flask.request.json['idToken']
    # Set session expiration to 5 days.
    expires_in = datetime.timedelta(days=5)
    try:
        # Create the session cookie. This will also verify the ID token in the process.
        # The session cookie will have the same claims as the ID token.
        session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in)
        response = flask.jsonify({'status': 'success'})
        # Set cookie policy for session cookie.
        expires = datetime.datetime.now() + expires_in
        response.set_cookie(
            'session', session_cookie, expires=expires, httponly=True, secure=True)
        return response
    except exceptions.FirebaseError:
        return flask.abort(401, 'Failed to create a session cookie')

जाना

return func(w http.ResponseWriter, r *http.Request) {
	// Get the ID token sent by the client
	defer r.Body.Close()
	idToken, err := getIDTokenFromBody(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// Set session expiration to 5 days.
	expiresIn := time.Hour * 24 * 5

	// Create the session cookie. This will also verify the ID token in the process.
	// The session cookie will have the same claims as the ID token.
	// To only allow session cookie setting on recent sign-in, auth_time in ID token
	// can be checked to ensure user was recently signed in before creating a session cookie.
	cookie, err := client.SessionCookie(r.Context(), idToken, expiresIn)
	if err != nil {
		http.Error(w, "Failed to create a session cookie", http.StatusInternalServerError)
		return
	}

	// Set cookie policy for session cookie.
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    cookie,
		MaxAge:   int(expiresIn.Seconds()),
		HttpOnly: true,
		Secure:   true,
	})
	w.Write([]byte(`{"status": "success"}`))
}

सी#

// POST: /sessionLogin
[HttpPost]
public async Task<ActionResult> Login([FromBody] LoginRequest request)
{
    // Set session expiration to 5 days.
    var options = new SessionCookieOptions()
    {
        ExpiresIn = TimeSpan.FromDays(5),
    };

    try
    {
        // Create the session cookie. This will also verify the ID token in the process.
        // The session cookie will have the same claims as the ID token.
        var sessionCookie = await FirebaseAuth.DefaultInstance
            .CreateSessionCookieAsync(request.IdToken, options);

        // Set cookie policy parameters as required.
        var cookieOptions = new CookieOptions()
        {
            Expires = DateTimeOffset.UtcNow.Add(options.ExpiresIn),
            HttpOnly = true,
            Secure = true,
        };
        this.Response.Cookies.Append("session", sessionCookie, cookieOptions);
        return this.Ok();
    }
    catch (FirebaseAuthException)
    {
        return this.Unauthorized("Failed to create a session cookie");
    }
}

संवेदनशील अनुप्रयोगों के लिए, सत्र कुकी जारी करने से पहले auth_time जांच की जानी चाहिए, जिससे आईडी टोकन चोरी होने की स्थिति में हमले की विंडो कम हो सके:

नोड.जे.एस

getAuth()
  .verifyIdToken(idToken)
  .then((decodedIdToken) => {
    // Only process if the user just signed in in the last 5 minutes.
    if (new Date().getTime() / 1000 - decodedIdToken.auth_time < 5 * 60) {
      // Create session cookie and set it.
      return getAuth().createSessionCookie(idToken, { expiresIn });
    }
    // A user that was not recently signed in is trying to set a session cookie.
    // To guard against ID token theft, require re-authentication.
    res.status(401).send('Recent sign in required!');
  });

जावा

// To ensure that cookies are set only on recently signed in users, check auth_time in
// ID token before creating a cookie.
FirebaseToken decodedToken = FirebaseAuth.getInstance().verifyIdToken(idToken);
long authTimeMillis = TimeUnit.SECONDS.toMillis(
    (long) decodedToken.getClaims().get("auth_time"));

// Only process if the user signed in within the last 5 minutes.
if (System.currentTimeMillis() - authTimeMillis < TimeUnit.MINUTES.toMillis(5)) {
  long expiresIn = TimeUnit.DAYS.toMillis(5);
  SessionCookieOptions options = SessionCookieOptions.builder()
      .setExpiresIn(expiresIn)
      .build();
  String sessionCookie = FirebaseAuth.getInstance().createSessionCookie(idToken, options);
  // Set cookie policy parameters as required.
  NewCookie cookie = new NewCookie("session", sessionCookie);
  return Response.ok().cookie(cookie).build();
}
// User did not sign in recently. To guard against ID token theft, require
// re-authentication.
return Response.status(Status.UNAUTHORIZED).entity("Recent sign in required").build();

अजगर

# To ensure that cookies are set only on recently signed in users, check auth_time in
# ID token before creating a cookie.
try:
    decoded_claims = auth.verify_id_token(id_token)
    # Only process if the user signed in within the last 5 minutes.
    if time.time() - decoded_claims['auth_time'] < 5 * 60:
        expires_in = datetime.timedelta(days=5)
        expires = datetime.datetime.now() + expires_in
        session_cookie = auth.create_session_cookie(id_token, expires_in=expires_in)
        response = flask.jsonify({'status': 'success'})
        response.set_cookie(
            'session', session_cookie, expires=expires, httponly=True, secure=True)
        return response
    # User did not sign in recently. To guard against ID token theft, require
    # re-authentication.
    return flask.abort(401, 'Recent sign in required')
except auth.InvalidIdTokenError:
    return flask.abort(401, 'Invalid ID token')
except exceptions.FirebaseError:
    return flask.abort(401, 'Failed to create a session cookie')

जाना

return func(w http.ResponseWriter, r *http.Request) {
	// Get the ID token sent by the client
	defer r.Body.Close()
	idToken, err := getIDTokenFromBody(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	decoded, err := client.VerifyIDToken(r.Context(), idToken)
	if err != nil {
		http.Error(w, "Invalid ID token", http.StatusUnauthorized)
		return
	}
	// Return error if the sign-in is older than 5 minutes.
	if time.Now().Unix()-decoded.Claims["auth_time"].(int64) > 5*60 {
		http.Error(w, "Recent sign-in required", http.StatusUnauthorized)
		return
	}

	expiresIn := time.Hour * 24 * 5
	cookie, err := client.SessionCookie(r.Context(), idToken, expiresIn)
	if err != nil {
		http.Error(w, "Failed to create a session cookie", http.StatusInternalServerError)
		return
	}
	http.SetCookie(w, &http.Cookie{
		Name:     "session",
		Value:    cookie,
		MaxAge:   int(expiresIn.Seconds()),
		HttpOnly: true,
		Secure:   true,
	})
	w.Write([]byte(`{"status": "success"}`))
}

सी#

// To ensure that cookies are set only on recently signed in users, check auth_time in
// ID token before creating a cookie.
var decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(idToken);
var authTime = new DateTime(1970, 1, 1).AddSeconds(
    (long)decodedToken.Claims["auth_time"]);

// Only process if the user signed in within the last 5 minutes.
if (DateTime.UtcNow - authTime < TimeSpan.FromMinutes(5))
{
    var options = new SessionCookieOptions()
    {
        ExpiresIn = TimeSpan.FromDays(5),
    };
    var sessionCookie = await FirebaseAuth.DefaultInstance.CreateSessionCookieAsync(
        idToken, options);
    // Set cookie policy parameters as required.
    this.Response.Cookies.Append("session", sessionCookie);
    return this.Ok();
}

// User did not sign in recently. To guard against ID token theft, require
// re-authentication.
return this.Unauthorized("Recent sign in required");

साइन-इन करने के बाद, वेबसाइट के सभी एक्सेस-सुरक्षित अनुभागों को सत्र कुकी की जांच करनी चाहिए और कुछ सुरक्षा नियमों के आधार पर प्रतिबंधित सामग्री परोसने से पहले इसे सत्यापित करना चाहिए।

नोड.जे.एस

// Whenever a user is accessing restricted content that requires authentication.
app.post('/profile', (req, res) => {
  const sessionCookie = req.cookies.session || '';
  // Verify the session cookie. In this case an additional check is added to detect
  // if the user's Firebase session was revoked, user deleted/disabled, etc.
  getAuth()
    .verifySessionCookie(sessionCookie, true /** checkRevoked */)
    .then((decodedClaims) => {
      serveContentForUser('/profile', req, res, decodedClaims);
    })
    .catch((error) => {
      // Session cookie is unavailable or invalid. Force user to login.
      res.redirect('/login');
    });
});

जावा

@POST
@Path("/profile")
public Response verifySessionCookie(@CookieParam("session") Cookie cookie) {
  String sessionCookie = cookie.getValue();
  try {
    // Verify the session cookie. In this case an additional check is added to detect
    // if the user's Firebase session was revoked, user deleted/disabled, etc.
    final boolean checkRevoked = true;
    FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(
        sessionCookie, checkRevoked);
    return serveContentForUser(decodedToken);
  } catch (FirebaseAuthException e) {
    // Session cookie is unavailable, invalid or revoked. Force user to login.
    return Response.temporaryRedirect(URI.create("/login")).build();
  }
}

अजगर

@app.route('/profile', methods=['POST'])
def access_restricted_content():
    session_cookie = flask.request.cookies.get('session')
    if not session_cookie:
        # Session cookie is unavailable. Force user to login.
        return flask.redirect('/login')

    # Verify the session cookie. In this case an additional check is added to detect
    # if the user's Firebase session was revoked, user deleted/disabled, etc.
    try:
        decoded_claims = auth.verify_session_cookie(session_cookie, check_revoked=True)
        return serve_content_for_user(decoded_claims)
    except auth.InvalidSessionCookieError:
        # Session cookie is invalid, expired or revoked. Force user to login.
        return flask.redirect('/login')

जाना

return func(w http.ResponseWriter, r *http.Request) {
	// Get the ID token sent by the client
	cookie, err := r.Cookie("session")
	if err != nil {
		// Session cookie is unavailable. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	// Verify the session cookie. In this case an additional check is added to detect
	// if the user's Firebase session was revoked, user deleted/disabled, etc.
	decoded, err := client.VerifySessionCookieAndCheckRevoked(r.Context(), cookie.Value)
	if err != nil {
		// Session cookie is invalid. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	serveContentForUser(w, r, decoded)
}

सी#

// POST: /profile
[HttpPost]
public async Task<ActionResult> Profile()
{
    var sessionCookie = this.Request.Cookies["session"];
    if (string.IsNullOrEmpty(sessionCookie))
    {
        // Session cookie is not available. Force user to login.
        return this.Redirect("/login");
    }

    try
    {
        // Verify the session cookie. In this case an additional check is added to detect
        // if the user's Firebase session was revoked, user deleted/disabled, etc.
        var checkRevoked = true;
        var decodedToken = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(
            sessionCookie, checkRevoked);
        return ViewContentForUser(decodedToken);
    }
    catch (FirebaseAuthException)
    {
        // Session cookie is invalid or revoked. Force user to login.
        return this.Redirect("/login");
    }
}

एडमिन SDK VerifySessionCookie API का उपयोग करके सत्र कुकीज़ सत्यापित करें। यह एक कम ओवरहेड ऑपरेशन है. सार्वजनिक प्रमाणपत्रों से प्रारंभ में पूछताछ की जाती है और उनके समाप्त होने तक कैश किया जाता है। सत्र कुकी सत्यापन बिना किसी अतिरिक्त नेटवर्क अनुरोध के कैश्ड सार्वजनिक प्रमाणपत्रों के साथ किया जा सकता है।

यदि कुकी अमान्य है, तो सुनिश्चित करें कि इसे साफ़ कर दिया गया है, और उपयोगकर्ता को फिर से साइन इन करने के लिए कहें। सत्र निरस्तीकरण की जांच के लिए एक अतिरिक्त विकल्प उपलब्ध है। ध्यान दें कि हर बार सत्र कुकी सत्यापित होने पर यह एक अतिरिक्त नेटवर्क अनुरोध जोड़ता है।

सुरक्षा कारणों से, फायरबेस सत्र कुकीज़ का उपयोग अन्य फायरबेस सेवाओं के साथ उनकी कस्टम वैधता अवधि के कारण नहीं किया जा सकता है, जिसे अधिकतम 2 सप्ताह की अवधि के लिए सेट किया जा सकता है। सर्वर साइड कुकीज़ का उपयोग करने वाले सभी एप्लिकेशन से अपेक्षा की जाती है कि वे इन कुकीज़ सर्वर साइड को सत्यापित करने के बाद अनुमति जांच लागू करें।

नोड.जे.एस

getAuth()
  .verifySessionCookie(sessionCookie, true)
  .then((decodedClaims) => {
    // Check custom claims to confirm user is an admin.
    if (decodedClaims.admin === true) {
      return serveContentForAdmin('/admin', req, res, decodedClaims);
    }
    res.status(401).send('UNAUTHORIZED REQUEST!');
  })
  .catch((error) => {
    // Session cookie is unavailable or invalid. Force user to login.
    res.redirect('/login');
  });

जावा

try {
  final boolean checkRevoked = true;
  FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(
      sessionCookie, checkRevoked);
  if (Boolean.TRUE.equals(decodedToken.getClaims().get("admin"))) {
    return serveContentForAdmin(decodedToken);
  }
  return Response.status(Status.UNAUTHORIZED).entity("Insufficient permissions").build();
} catch (FirebaseAuthException e) {
  // Session cookie is unavailable, invalid or revoked. Force user to login.
  return Response.temporaryRedirect(URI.create("/login")).build();
}

अजगर

try:
    decoded_claims = auth.verify_session_cookie(session_cookie, check_revoked=True)
    # Check custom claims to confirm user is an admin.
    if decoded_claims.get('admin') is True:
        return serve_content_for_admin(decoded_claims)

    return flask.abort(401, 'Insufficient permissions')
except auth.InvalidSessionCookieError:
    # Session cookie is invalid, expired or revoked. Force user to login.
    return flask.redirect('/login')

जाना

return func(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("session")
	if err != nil {
		// Session cookie is unavailable. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	decoded, err := client.VerifySessionCookieAndCheckRevoked(r.Context(), cookie.Value)
	if err != nil {
		// Session cookie is invalid. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	// Check custom claims to confirm user is an admin.
	if decoded.Claims["admin"] != true {
		http.Error(w, "Insufficient permissions", http.StatusUnauthorized)
		return
	}

	serveContentForAdmin(w, r, decoded)
}

सी#

try
{
    var checkRevoked = true;
    var decodedToken = await FirebaseAuth.DefaultInstance.VerifySessionCookieAsync(
        sessionCookie, checkRevoked);
    object isAdmin;
    if (decodedToken.Claims.TryGetValue("admin", out isAdmin) && (bool)isAdmin)
    {
        return ViewContentForAdmin(decodedToken);
    }

    return this.Unauthorized("Insufficient permissions");
}
catch (FirebaseAuthException)
{
    // Session cookie is invalid or revoked. Force user to login.
    return this.Redirect("/login");
}

साइन आउट

जब कोई उपयोगकर्ता क्लाइंट साइड से साइन आउट करता है, तो इसे एंडपॉइंट के माध्यम से सर्वर साइड पर संभालें। POST/GET अनुरोध के परिणामस्वरूप सत्र कुकी साफ़ हो जानी चाहिए। ध्यान दें कि भले ही कुकी साफ़ हो गई हो, यह अपनी प्राकृतिक समाप्ति तक सक्रिय रहती है।

नोड.जे.एस

app.post('/sessionLogout', (req, res) => {
  res.clearCookie('session');
  res.redirect('/login');
});

जावा

@POST
@Path("/sessionLogout")
public Response clearSessionCookie(@CookieParam("session") Cookie cookie) {
  final int maxAge = 0;
  NewCookie newCookie = new NewCookie(cookie, null, maxAge, true);
  return Response.temporaryRedirect(URI.create("/login")).cookie(newCookie).build();
}

अजगर

@app.route('/sessionLogout', methods=['POST'])
def session_logout():
    response = flask.make_response(flask.redirect('/login'))
    response.set_cookie('session', expires=0)
    return response

जाना

return func(w http.ResponseWriter, r *http.Request) {
	http.SetCookie(w, &http.Cookie{
		Name:   "session",
		Value:  "",
		MaxAge: 0,
	})
	http.Redirect(w, r, "/login", http.StatusFound)
}

सी#

// POST: /sessionLogout
[HttpPost]
public ActionResult ClearSessionCookie()
{
    this.Response.Cookies.Delete("session");
    return this.Redirect("/login");
}

निरस्तीकरण एपीआई को कॉल करने से सत्र निरस्त हो जाता है और उपयोगकर्ता के सभी अन्य सत्र भी निरस्त हो जाते हैं, जिससे नए लॉगिन को बाध्य होना पड़ता है। संवेदनशील अनुप्रयोगों के लिए, छोटी सत्र अवधि की सलाह दी जाती है।

नोड.जे.एस

app.post('/sessionLogout', (req, res) => {
  const sessionCookie = req.cookies.session || '';
  res.clearCookie('session');
  getAuth()
    .verifySessionCookie(sessionCookie)
    .then((decodedClaims) => {
      return getAuth().revokeRefreshTokens(decodedClaims.sub);
    })
    .then(() => {
      res.redirect('/login');
    })
    .catch((error) => {
      res.redirect('/login');
    });
});

जावा

@POST
@Path("/sessionLogout")
public Response clearSessionCookieAndRevoke(@CookieParam("session") Cookie cookie) {
  String sessionCookie = cookie.getValue();
  try {
    FirebaseToken decodedToken = FirebaseAuth.getInstance().verifySessionCookie(sessionCookie);
    FirebaseAuth.getInstance().revokeRefreshTokens(decodedToken.getUid());
    final int maxAge = 0;
    NewCookie newCookie = new NewCookie(cookie, null, maxAge, true);
    return Response.temporaryRedirect(URI.create("/login")).cookie(newCookie).build();
  } catch (FirebaseAuthException e) {
    return Response.temporaryRedirect(URI.create("/login")).build();
  }
}

अजगर

@app.route('/sessionLogout', methods=['POST'])
def session_logout():
    session_cookie = flask.request.cookies.get('session')
    try:
        decoded_claims = auth.verify_session_cookie(session_cookie)
        auth.revoke_refresh_tokens(decoded_claims['sub'])
        response = flask.make_response(flask.redirect('/login'))
        response.set_cookie('session', expires=0)
        return response
    except auth.InvalidSessionCookieError:
        return flask.redirect('/login')

जाना

return func(w http.ResponseWriter, r *http.Request) {
	cookie, err := r.Cookie("session")
	if err != nil {
		// Session cookie is unavailable. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}

	decoded, err := client.VerifySessionCookie(r.Context(), cookie.Value)
	if err != nil {
		// Session cookie is invalid. Force user to login.
		http.Redirect(w, r, "/login", http.StatusFound)
		return
	}
	if err := client.RevokeRefreshTokens(r.Context(), decoded.UID); err != nil {
		http.Error(w, "Failed to revoke refresh token", http.StatusInternalServerError)
		return
	}

	http.SetCookie(w, &http.Cookie{
		Name:   "session",
		Value:  "",
		MaxAge: 0,
	})
	http.Redirect(w, r, "/login", http.StatusFound)
}

सी#

// POST: /sessionLogout
[HttpPost]
public async Task<ActionResult> ClearSessionCookieAndRevoke()
{
    var sessionCookie = this.Request.Cookies["session"];
    try
    {
        var decodedToken = await FirebaseAuth.DefaultInstance
            .VerifySessionCookieAsync(sessionCookie);
        await FirebaseAuth.DefaultInstance.RevokeRefreshTokensAsync(decodedToken.Uid);
        this.Response.Cookies.Delete("session");
        return this.Redirect("/login");
    }
    catch (FirebaseAuthException)
    {
        return this.Redirect("/login");
    }
}

तृतीय-पक्ष JWT लाइब्रेरी का उपयोग करके सत्र कुकीज़ सत्यापित करें

यदि आपका बैकएंड ऐसी भाषा में है जो फायरबेस एडमिन एसडीके द्वारा समर्थित नहीं है, तो भी आप सत्र कुकीज़ को सत्यापित कर सकते हैं। सबसे पहले, अपनी भाषा के लिए एक तृतीय-पक्ष JWT लाइब्रेरी ढूंढें । फिर, सत्र कुकी के हेडर, पेलोड और हस्ताक्षर को सत्यापित करें।

सत्यापित करें कि सत्र कुकी का हेडर निम्नलिखित बाधाओं के अनुरूप है:

फायरबेस सत्र कुकी हेडर दावे
alg कलन विधि "RS256"
kid कुंजी आईडी https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys पर सूचीबद्ध सार्वजनिक कुंजी में से एक के अनुरूप होना चाहिए

सत्यापित करें कि सत्र कुकी का पेलोड निम्नलिखित बाधाओं के अनुरूप है:

फायरबेस सत्र कुकी पेलोड दावे
exp समय सीमा समाप्ति समय भविष्य में होना चाहिए. UNIX युग के बाद से समय को सेकंड में मापा जाता है। समाप्ति तिथि कुकी बनाते समय प्रदान की गई कस्टम अवधि के आधार पर निर्धारित की जाती है।
iat जारी-समय पर अतीत में होना चाहिए. UNIX युग के बाद से समय को सेकंड में मापा जाता है।
aud श्रोता यह आपकी फायरबेस प्रोजेक्ट आईडी होनी चाहिए, जो आपके फायरबेस प्रोजेक्ट के लिए विशिष्ट पहचानकर्ता है, जो उस प्रोजेक्ट के कंसोल के यूआरएल में पाया जा सकता है।
iss जारीकर्ता "https://session.firebase.google.com/<projectId>" " होना चाहिए, जहां <projectId> वही प्रोजेक्ट आईडी है जिसका उपयोग ऊपर दिए गए aud के लिए किया गया है।
sub विषय एक गैर-रिक्त स्ट्रिंग होनी चाहिए और उपयोगकर्ता या डिवाइस का uid होना चाहिए।
auth_time प्रमाणीकरण समय अतीत में होना चाहिए. वह समय जब उपयोगकर्ता ने प्रमाणित किया। यह सत्र कुकी बनाने के लिए उपयोग किए गए आईडी टोकन के auth_time से मेल खाता है।

अंत में, सुनिश्चित करें कि सत्र कुकी पर टोकन के बच्चे के दावे के अनुरूप निजी कुंजी द्वारा हस्ताक्षर किया गया था। https://www.googleapis.com/identitytoolkit/v3/relyingparty/publicKeys से सार्वजनिक कुंजी प्राप्त करें और हस्ताक्षर सत्यापित करने के लिए JWT लाइब्रेरी का उपयोग करें। सार्वजनिक कुंजियों को कब ताज़ा करना है यह निर्धारित करने के लिए उस समापन बिंदु से प्रतिक्रिया के Cache-Control हेडर में अधिकतम आयु के मान का उपयोग करें।

यदि उपरोक्त सभी सत्यापन सफल हैं, तो आप सत्र कुकी के विषय ( sub ) को संबंधित उपयोगकर्ता या डिवाइस के यूआईडी के रूप में उपयोग कर सकते हैं।