उपयोगकर्ता को साइन इन करने दें

Classroom ऐड-ऑन के लिए सिलसिलेवार तरीके से निर्देश देने की सीरीज़ का यह दूसरा चरण है.

सिलसिलेवार तरीके से दिए गए इस निर्देश में, आपने वेब ऐप्लिकेशन में 'Google साइन इन' को जोड़ा है. Classroom ऐड-ऑन के लिए ऐसा करना ज़रूरी है. आने वाले समय में एपीआई को किए जाने वाले सभी कॉल के लिए, अनुमति देने वाले इस फ़्लो के क्रेडेंशियल का इस्तेमाल करें.

कदम-दर-कदम निर्देश देने के लिए, आपने ये काम किए हैं:

  • iframe में सेशन डेटा बनाए रखने के लिए अपने वेब ऐप्लिकेशन को कॉन्फ़िगर करें.
  • Google OAuth 2.0 के सर्वर-टू-सर्वर साइन इन फ़्लो को लागू करना.
  • OAuth 2.0 एपीआई के लिए कॉल जारी करें.
  • एपीआई कॉल को अनुमति देने, साइन आउट करने, और उनकी जांच करने में मदद करने के लिए दूसरे रूट बनाएं.

इसके बाद, आपके पास अपने वेब ऐप्लिकेशन में उपयोगकर्ताओं को पूरी तरह से अनुमति देने और Google API को कॉल जारी करने का विकल्प होगा.

अनुमति देने के फ़्लो को समझना

Google API, पुष्टि करने और अनुमति देने के लिए, OAuth 2.0 प्रोटोकॉल का इस्तेमाल करता है. Google के OAuth को लागू करने की पूरी जानकारी, Google Identity OAuth गाइड में उपलब्ध है.

आपके ऐप्लिकेशन के क्रेडेंशियल, Google Cloud में मैनेज किए जाते हैं. इन्हें बनाने के बाद, किसी उपयोगकर्ता को अनुमति देने और उसकी पुष्टि करने के लिए, चार चरणों वाली प्रोसेस लागू करें:

  1. अनुमति देने का अनुरोध करें. इस अनुरोध के तहत, कॉलबैक यूआरएल दें. प्रक्रिया पूरी होने पर, आपको अनुमति देने वाला यूआरएल मिलेगा.
  2. उपयोगकर्ता को अनुमति देने वाले यूआरएल पर रीडायरेक्ट करें. दिखने वाला पेज, उपयोगकर्ता को उन अनुमतियों के बारे में बताता है जो आपके ऐप्लिकेशन को चाहिए. साथ ही, पेज पर उन्हें ऐक्सेस देने के लिए कहा जाता है. पूरा होने पर, उपयोगकर्ता को कॉलबैक यूआरएल पर रूट कर दिया जाता है.
  3. अपने कॉलबैक वाले रास्ते पर ऑथराइज़ेशन कोड पाएं. ऐक्सेस टोकन और रीफ़्रेश टोकन के लिए, ऑथराइज़ेशन कोड को एक्सचेंज करें.
  4. टोकन का इस्तेमाल करके, Google API को कॉल करें.

OAuth 2.0 क्रेडेंशियल पाना

पक्का करें कि आपने OAuth क्रेडेंशियल बनाए और डाउनलोड किए हैं. जैसा कि खास जानकारी देने वाले पेज पर बताया गया है. उपयोगकर्ता को साइन इन करने के लिए, आपके प्रोजेक्ट को इन क्रेडेंशियल का इस्तेमाल करना होगा.

अनुमति देने का फ़्लो लागू करना

ऊपर बताए गए फ़्लो को समझने के लिए, हमारे वेब ऐप्लिकेशन में लॉजिक और रूट जोड़ें. इनमें ये सुविधाएं भी शामिल हैं:

  • लैंडिंग पेज पर जाकर, अनुमति देने की प्रक्रिया शुरू करें.
  • अनुमति देने का अनुरोध करें और अनुमति देने वाले सर्वर से मिलने वाले रिस्पॉन्स को मैनेज करें.
  • सेव किए गए क्रेडेंशियल मिटाएं.
  • ऐप्लिकेशन को दी गई अनुमतियां वापस लेना.
  • एपीआई कॉल की जांच करें.

अनुमति देना शुरू करें

अगर ज़रूरी हो, तो अनुमति देने का फ़्लो शुरू करने के लिए, अपने लैंडिंग पेज में बदलाव करें. ऐड-ऑन दो संभावित स्थितियों में हो सकता है; मौजूदा सेशन में या तो सेव किए गए टोकन मौजूद हैं या आपको OAuth 2.0 सर्वर से टोकन लेने की ज़रूरत है. अगर सेशन में टोकन हैं, तो टेस्ट एपीआई कॉल करें या किसी अन्य तरीके से उपयोगकर्ता को साइन इन करने का प्रॉम्प्ट भेजें.

Python

routes.py फ़ाइल खोलें. सबसे पहले, iframe सुरक्षा से जुड़े सुझावों के हिसाब से, कुछ कॉन्सटेंट और हमारा कुकी कॉन्फ़िगरेशन सेट करें.

# The file that contains the OAuth 2.0 client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"

# The OAuth 2.0 access scopes to request.
# These scopes must match the scopes in your Google Cloud project's OAuth Consent
# Screen: https://console.cloud.google.com/apis/credentials/consent
SCOPES = [
    "openid",
    "https://www.googleapis.com/auth/userinfo.profile",
    "https://www.googleapis.com/auth/userinfo.email",
    "https://www.googleapis.com/auth/classroom.addons.teacher",
    "https://www.googleapis.com/auth/classroom.addons.student"
]

# Flask cookie configurations.
app.config.update(
    SESSION_COOKIE_SECURE=True,
    SESSION_COOKIE_HTTPONLY=True,
    SESSION_COOKIE_SAMESITE="None",
)

अपने ऐड-ऑन लैंडिंग रूट पर जाएं (उदाहरण वाली फ़ाइल में यह /classroom-addon है). अगर सेशन में "क्रेडेंशियल" कुंजी नहीं है, तो साइन-इन पेज को रेंडर करने के लिए लॉजिक जोड़ें.

@app.route("/classroom-addon")
def classroom_addon():
    if "credentials" not in flask.session:
        return flask.render_template("authorization.html")

    return flask.render_template(
        "addon-discovery.html",
        message="You've reached the addon discovery page.")

Java

सिलसिलेवार तरीके से दिए गए निर्देशों का कोड, step_02_sign_in मॉड्यूल में देखा जा सकता है.

application.properties फ़ाइल खोलें और ऐसा सेशन कॉन्फ़िगरेशन जोड़ें जो iframe सुरक्षा से जुड़े सुझावों के मुताबिक हो.

# iFrame security recommendations call for cookies to have the HttpOnly and
# secure attribute set
server.servlet.session.cookie.http-only=true
server.servlet.session.cookie.secure=true

# Ensures that the session is maintained across the iframe and sign-in pop-up.
server.servlet.session.cookie.same-site=none

कंट्रोलर फ़ाइल में एंडपॉइंट के पीछे के लॉजिक को हैंडल करने के लिए, सर्विस क्लास (step_02_sign_in मॉड्यूल में AuthService.java) बनाएं. साथ ही, रीडायरेक्ट यूआरआई, क्लाइंट सीक्रेट फ़ाइल की जगह, और आपके ऐड-ऑन के लिए ज़रूरी स्कोप सेट अप करें. जब उपयोगकर्ता आपके ऐप्लिकेशन को अनुमति देते हैं, तब रीडायरेक्ट यूआरआई का इस्तेमाल करके उन्हें किसी खास यूआरआई पर भेजा जाता है. अपनी client_secret.json फ़ाइल कहां रखें, यह जानने के लिए सोर्स कोड में README.md का प्रोजेक्ट सेट अप सेक्शन देखें.

@Service
public class AuthService {
    private static final String REDIRECT_URI = "https://localhost:5000/callback";
    private static final String CLIENT_SECRET_FILE = "client_secret.json";
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
    private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance();

    private static final String[] REQUIRED_SCOPES = {
        "https://www.googleapis.com/auth/userinfo.profile",
        "https://www.googleapis.com/auth/userinfo.email",
        "https://www.googleapis.com/auth/classroom.addons.teacher",
        "https://www.googleapis.com/auth/classroom.addons.student"
    };

    /** Creates and returns a Collection object with all requested scopes.
    *   @return Collection of scopes requested by the application.
    */
    public static Collection<String> getScopes() {
        return new ArrayList<>(Arrays.asList(REQUIRED_SCOPES));
    }
}

कंट्रोलर फ़ाइल खोलें (step_02_sign_in मॉड्यूल में AuthController.java) और अगर सेशन में credentials कुंजी नहीं है, तो लैंडिंग रूट में साइन-इन पेज को रेंडर करने के लिए लॉजिक जोड़ें.

@GetMapping(value = {"/start-auth-flow"})
public String startAuthFlow(Model model) {
    try {
        return "authorization";
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

@GetMapping(value = {"/addon-discovery"})
public String addon_discovery(HttpSession session, Model model) {
    try {
        if (session == null || session.getAttribute("credentials") == null) {
            return startAuthFlow(model);
        }
        return "addon-discovery";
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

आपके अनुमति देने वाले पेज पर, उपयोगकर्ता के लिए "साइन इन" करने का लिंक या बटन होना चाहिए. इस पर क्लिक करने से उपयोगकर्ता को authorize रूट पर रीडायरेक्ट हो जाना चाहिए.

अनुमति देने का अनुरोध करें

अनुमति का अनुरोध करने के लिए, उपयोगकर्ता को पुष्टि करने वाला यूआरएल बनाकर उस पर रीडायरेक्ट करें. इस यूआरएल में कई तरह की जानकारी शामिल होती है, जैसे कि अनुमति के बाद के लिए अनुरोध किए गए दायरों, डेस्टिनेशन रूट, और वेब ऐप्लिकेशन का क्लाइंट आईडी. आप इन्हें अनुमति देने के इस सैंपल यूआरएल में देख सकते हैं.

Python

अपनी routes.py फ़ाइल में यह इंपोर्ट जोड़ें.

import google_auth_oauthlib.flow

नया रास्ता /authorize बनाएं. google_auth_oauthlib.flow.Flow का इंस्टेंस बनाएं. हमारा सुझाव है कि ऐसा करने के लिए, शामिल किए गए from_client_secrets_file तरीके का इस्तेमाल करें.

@app.route("/authorize")
def authorize():
    # Create flow instance to manage the OAuth 2.0 Authorization Grant Flow
    # steps.
    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES)

flow के redirect_uri को सेट करें; यह वह रूट है जिस पर आप उपयोगकर्ताओं को आपके ऐप्लिकेशन को अनुमति देने के बाद वापस लाने की कोशिश करते हैं. यह नीचे दिए गए उदाहरण में /callback है.

# The URI created here must exactly match one of the authorized redirect
# URIs for the OAuth 2.0 client, which you configured in the API Console. If
# this value doesn't match an authorized URI, you will get a
# "redirect_uri_mismatch" error.
flow.redirect_uri = flask.url_for("callback", _external=True)

authorization_url और state बनाने के लिए फ़्लो ऑब्जेक्ट का इस्तेमाल करें. सेशन में state को सेव करें. इसका इस्तेमाल बाद में, सर्वर के रिस्पॉन्स की प्रामाणिकता की पुष्टि करने के लिए किया जाता है. आखिर में, उपयोगकर्ता को authorization_url पर रीडायरेक्ट करें.

authorization_url, state = flow.authorization_url(
    # Enable offline access so that you can refresh an access token without
    # re-prompting the user for permission. Recommended for web server apps.
    access_type="offline",
    # Enable incremental authorization. Recommended as a best practice.
    include_granted_scopes="true")

# Store the state so the callback can verify the auth server response.
flask.session["state"] = state

# Redirect the user to the OAuth authorization URL.
return flask.redirect(authorization_url)

Java

फ़्लो ऑब्जेक्ट को इंस्टैंशिएट करने के लिए, AuthService.java फ़ाइल में यहां दिए गए तरीके जोड़ें. इसके बाद, अनुमति देने वाले यूआरएल को फिर से पाने के लिए, इसका इस्तेमाल करें:

  • getClientSecrets() तरीका, क्लाइंट सीक्रेट फ़ाइल को पढ़ता है और GoogleClientSecrets ऑब्जेक्ट बनाता है.
  • getFlow() वाला तरीका, GoogleAuthorizationCodeFlow का इंस्टेंस बनाता है.
  • अनुमति देने वाला यूआरएल फिर से पाने के लिए, authorize() वाला तरीका GoogleAuthorizationCodeFlow ऑब्जेक्ट, state पैरामीटर, और रीडायरेक्ट यूआरआई का इस्तेमाल करता है. state पैरामीटर का इस्तेमाल, ऑथराइज़ेशन सर्वर से मिले रिस्पॉन्स की प्रामाणिकता की पुष्टि करने के लिए किया जाता है. इसके बाद, यह तरीका अनुमति देने वाले यूआरएल और state पैरामीटर के साथ एक मैप दिखाता है.
/** Reads the client secret file downloaded from Google Cloud.
 *   @return GoogleClientSecrets read in from client secret file. */
public GoogleClientSecrets getClientSecrets() throws Exception {
    try {
        InputStream in = SignInApplication.class.getClassLoader()
            .getResourceAsStream(CLIENT_SECRET_FILE);
        if (in == null) {
            throw new FileNotFoundException("Client secret file not found: "
                +   CLIENT_SECRET_FILE);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets
            .load(JSON_FACTORY, new InputStreamReader(in));
        return clientSecrets;
    } catch (Exception e) {
        throw e;
    }
}

/** Builds and returns authorization code flow.
*   @return GoogleAuthorizationCodeFlow object used to retrieve an access
*   token and refresh token for the application.
*   @throws Exception if reading client secrets or building code flow object
*   is unsuccessful.
*/
public GoogleAuthorizationCodeFlow getFlow() throws Exception {
    try {
        GoogleAuthorizationCodeFlow authorizationCodeFlow =
            new GoogleAuthorizationCodeFlow.Builder(
                HTTP_TRANSPORT,
                JSON_FACTORY,
                getClientSecrets(),
                getScopes())
                .setAccessType("offline")
                .build();
        return authorizationCodeFlow;
    } catch (Exception e) {
        throw e;
    }
}

/** Builds and returns a map with the authorization URL, which allows the
*   user to give the app permission to their account, and the state parameter,
*   which is used to prevent cross site request forgery.
*   @return map with authorization URL and state parameter.
*   @throws Exception if building the authorization URL is unsuccessful.
*/
public HashMap authorize() throws Exception {
    HashMap<String, String> authDataMap = new HashMap<>();
    try {
        String state = new BigInteger(130, new SecureRandom()).toString(32);
        authDataMap.put("state", state);

        GoogleAuthorizationCodeFlow flow = getFlow();
        String authUrl = flow
            .newAuthorizationUrl()
            .setState(state)
            .setRedirectUri(REDIRECT_URI)
            .build();
        String url = authUrl;
        authDataMap.put("url", url);

        return authDataMap;
    } catch (Exception e) {
        throw e;
    }
}

कंट्रोलर क्लास में सर्विस क्लास का इंस्टेंस बनाने के लिए, कंस्ट्रक्टर इंजेक्शन का इस्तेमाल करें.

/** Declare AuthService to be used in the Controller class constructor. */
private final AuthService authService;

/** AuthController constructor. Uses constructor injection to instantiate
*   the AuthService and UserRepository classes.
*   @param authService the service class that handles the implementation logic
*   of requests.
*/
public AuthController(AuthService authService) {
    this.authService = authService;
}

/authorize एंडपॉइंट को कंट्रोलर क्लास में जोड़ें. यह एंडपॉइंट, state पैरामीटर और ऑथराइज़ेशन यूआरएल को पाने के लिए, AuthService authorize() तरीके को कॉल करता है. इसके बाद, एंडपॉइंट सेशन में state पैरामीटर को सेव करता है और उपयोगकर्ताओं को अनुमति वाले यूआरएल पर रीडायरेक्ट करता है.

/** Redirects the sign-in pop-up to the authorization URL.
*   @param response the current response to pass information to.
*   @param session the current session.
*   @throws Exception if redirection to the authorization URL is unsuccessful.
*/
@GetMapping(value = {"/authorize"})
public void authorize(HttpServletResponse response, HttpSession session)
    throws Exception {
    try {
        HashMap authDataMap = authService.authorize();
        String authUrl = authDataMap.get("url").toString();
        String state = authDataMap.get("state").toString();
        session.setAttribute("state", state);
        response.sendRedirect(authUrl);
    } catch (Exception e) {
        throw e;
    }
}

सर्वर के रिस्पॉन्स को मैनेज करना

अनुमति देने के बाद, उपयोगकर्ता पिछले चरण से redirect_uri रूट पर वापस आ जाता है. ऊपर दिए गए उदाहरण में, यह रास्ता /callback है.

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

Python

अपनी Flask सर्वर फ़ाइल में, ये इंपोर्ट जोड़ें.

import google.oauth2.credentials
import googleapiclient.discovery

अपने सर्वर पर रूट जोड़ें. google_auth_oauthlib.flow.Flow का एक दूसरा इंस्टेंस बनाएं, लेकिन इस बार पिछले चरण में सेव की गई स्थिति का ही फिर से इस्तेमाल करें.

@app.route("/callback")
def callback():
    state = flask.session["state"]

    flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
        CLIENT_SECRETS_FILE, scopes=SCOPES, state=state)
    flow.redirect_uri = flask.url_for("callback", _external=True)

इसके बाद, ऐक्सेस का अनुरोध करें और टोकन रीफ़्रेश करें. अच्छी बात यह है कि ऐसा करने के लिए, flow ऑब्जेक्ट में fetch_token तरीका भी मौजूद है. इस तरीके में code या authorization_response आर्ग्युमेंट की ज़रूरत होती है. authorization_response का इस्तेमाल करें, क्योंकि यह अनुरोध से पूरा यूआरएल है.

authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)

अब आपके पास पूरे क्रेडेंशियल हैं! सेशन में उन्हें स्टोर करें, ताकि उन्हें दूसरे तरीकों या रूट से फिर से हासिल किया जा सके. इसके बाद, उन्हें किसी ऐड-ऑन लैंडिंग पेज पर रीडायरेक्ट करें.

credentials = flow.credentials
flask.session["credentials"] = {
    "token": credentials.token,
    "refresh_token": credentials.refresh_token,
    "token_uri": credentials.token_uri,
    "client_id": credentials.client_id,
    "client_secret": credentials.client_secret,
    "scopes": credentials.scopes
}

# Close the pop-up by rendering an HTML page with a script that redirects
# the owner and closes itself. This can be done with a bit of JavaScript:
# <script>
#     window.opener.location.href = "{{ url_for('classroom_addon') }}";
#     window.close();
# </script>
return flask.render_template("close-me.html")

Java

अपनी सर्विस क्लास में ऐसा तरीका जोड़ें जो ऑथराइज़ेशन यूआरएल से मिले रीडायरेक्ट से मिले ऑथराइज़ेशन कोड को पास करके, Credentials ऑब्जेक्ट को दिखाता हो. इस Credentials ऑब्जेक्ट का इस्तेमाल, बाद में ऐक्सेस टोकन को फिर से पाने और टोकन को रीफ़्रेश करने के लिए किया जाता है.

/** Returns the required credentials to access Google APIs.
*   @param authorizationCode the authorization code provided by the
*   authorization URL that's used to obtain credentials.
*   @return the credentials that were retrieved from the authorization flow.
*   @throws Exception if retrieving credentials is unsuccessful.
*/
public Credential getAndSaveCredentials(String authorizationCode) throws Exception {
    try {
        GoogleAuthorizationCodeFlow flow = getFlow();
        GoogleClientSecrets googleClientSecrets = getClientSecrets();
        TokenResponse tokenResponse = flow.newTokenRequest(authorizationCode)
            .setClientAuthentication(new ClientParametersAuthentication(
                googleClientSecrets.getWeb().getClientId(),
                googleClientSecrets.getWeb().getClientSecret()))
            .setRedirectUri(REDIRECT_URI)
            .execute();
        Credential credential = flow.createAndStoreCredential(tokenResponse, null);
        return credential;
    } catch (Exception e) {
        throw e;
    }
}

कंट्रोलर के लिए अपने रीडायरेक्ट यूआरआई के लिए कोई एंडपॉइंट जोड़ें. अनुरोध से ऑथराइज़ेशन कोड और state पैरामीटर वापस पाएं. इस state पैरामीटर की तुलना, सेशन में सेव किए गए state एट्रिब्यूट से करें. अगर वे मेल खाते हैं, तो ऑथराइज़ेशन फ़्लो के साथ जारी रखें. अगर वे मैच नहीं करते हैं, तो गड़बड़ी दिखाता है.

इसके बाद, AuthService getAndSaveCredentials तरीके को कॉल करें और ऑथराइज़ेशन कोड को पैरामीटर के तौर पर पास करें. Credentials ऑब्जेक्ट को वापस पाने के बाद, उसे सेशन में सेव करें. इसके बाद, डायलॉग बॉक्स बंद करें और उपयोगकर्ता को ऐड-ऑन लैंडिंग पेज पर रीडायरेक्ट करें.

/** Handles the redirect URL to grant the application access to the user's
*   account.
*   @param request the current request used to obtain the authorization code
*   and state parameter from.
*   @param session the current session.
*   @param response the current response to pass information to.
*   @param model the Model interface to pass error information that's
*   displayed on the error page.
*   @return the close-pop-up template if authorization is successful, or the
*   onError method to handle and display the error message.
*/
@GetMapping(value = {"/callback"})
public String callback(HttpServletRequest request, HttpSession session,
    HttpServletResponse response, Model model) {
    try {
        String authCode = request.getParameter("code");
        String requestState = request.getParameter("state");
        String sessionState = session.getAttribute("state").toString();
        if (!requestState.equals(sessionState)) {
            response.setStatus(401);
            return onError("Invalid state parameter.", model);
        }
        Credential credentials = authService.getAndSaveCredentials(authCode);
        session.setAttribute("credentials", credentials);
        return "close-pop-up";
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

एपीआई कॉल की जांच करें

फ़्लो पूरा होने के बाद, अब Google API को कॉल जारी किए जा सकते हैं!

उदाहरण के लिए, उपयोगकर्ता की प्रोफ़ाइल की जानकारी मांगें. OAuth 2.0 API की मदद से, उपयोगकर्ता की जानकारी पाने का अनुरोध किया जा सकता है.

Python

OAuth 2.0 Discovery API के लिए दस्तावेज़ पढ़ें अपने-आप भरा हुआ UserInfo ऑब्जेक्ट पाने के लिए, इसका इस्तेमाल करें.

# Retrieve the credentials from the session data and construct a
# Credentials instance.
credentials = google.oauth2.credentials.Credentials(
    **flask.session["credentials"])

# Construct the OAuth 2.0 v2 discovery API library.
user_info_service = googleapiclient.discovery.build(
    serviceName="oauth2", version="v2", credentials=credentials)

# Request and store the username in the session.
# This allows it to be used in other methods or in an HTML template.
flask.session["username"] = (
    user_info_service.userinfo().get().execute().get("name"))

Java

सेवा क्लास में ऐसा तरीका बनाएं जो Credentials को पैरामीटर के तौर पर इस्तेमाल करके, UserInfo ऑब्जेक्ट बनाता हो.

/** Obtains the Userinfo object by passing in the required credentials.
*   @param credentials retrieved from the authorization flow.
*   @return the Userinfo object for the currently signed-in user.
*   @throws IOException if creating UserInfo service or obtaining the
*   Userinfo object is unsuccessful.
*/
public Userinfo getUserInfo(Credential credentials) throws IOException {
    try {
        Oauth2 userInfoService = new Oauth2.Builder(
            new NetHttpTransport(),
            new GsonFactory(),
            credentials).build();
        Userinfo userinfo = userInfoService.userinfo().get().execute();
        return userinfo;
    } catch (Exception e) {
        throw e;
    }
}

/test एंडपॉइंट को उस कंट्रोलर में जोड़ें जो उपयोगकर्ता का ईमेल दिखाता है.

/** Returns the test request page with the user's email.
*   @param session the current session.
*   @param model the Model interface to pass error information that's
*   displayed on the error page.
*   @return the test page that displays the current user's email or the
*   onError method to handle and display the error message.
*/
@GetMapping(value = {"/test"})
public String test(HttpSession session, Model model) {
    try {
        Credential credentials = (Credential) session.getAttribute("credentials");
        Userinfo userInfo = authService.getUserInfo(credentials);
        String userInfoEmail = userInfo.getEmail();
        if (userInfoEmail != null) {
            model.addAttribute("userEmail", userInfoEmail);
        } else {
            return onError("Could not get user email.", model);
        }
        return "test";
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

क्रेडेंशियल हटाएं

किसी उपयोगकर्ता को मौजूदा सेशन से हटाकर, उसके क्रेडेंशियल "साफ़" किए जा सकते हैं. इसकी मदद से, ऐड-ऑन के लैंडिंग पेज पर रूटिंग की जांच की जा सकती है.

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

Python

@app.route("/clear")
def clear_credentials():
    if "credentials" in flask.session:
        del flask.session["credentials"]
        del flask.session["username"]

    return flask.render_template("signed-out.html")

इसके अलावा, flask.session.clear() का इस्तेमाल करें, लेकिन अगर सेशन में दूसरी वैल्यू सेव हैं, तो इससे अनचाहे असर पड़ सकते हैं.

Java

कंट्रोलर में, /clear एंडपॉइंट जोड़ें.

/** Clears the credentials in the session and returns the sign-out
*   confirmation page.
*   @param session the current session.
*   @return the sign-out confirmation page.
*/
@GetMapping(value = {"/clear"})
public String clear(HttpSession session) {
    try {
        if (session != null && session.getAttribute("credentials") != null) {
            session.removeAttribute("credentials");
        }
        return "sign-out";
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

ऐप्लिकेशन को दी गई अनुमति वापस लेना

उपयोगकर्ता https://oauth2.googleapis.com/revoke को POST अनुरोध भेजकर, आपके ऐप्लिकेशन को दी गई अनुमति वापस ले सकता है. अनुरोध में उपयोगकर्ता का ऐक्सेस टोकन होना चाहिए.

Python

import requests

@app.route("/revoke")
def revoke():
    if "credentials" not in flask.session:
        return flask.render_template("addon-discovery.html",
                            message="You need to authorize before " +
                            "attempting to revoke credentials.")

    credentials = google.oauth2.credentials.Credentials(
        **flask.session["credentials"])

    revoke = requests.post(
        "https://oauth2.googleapis.com/revoke",
        params={"token": credentials.token},
        headers={"content-type": "application/x-www-form-urlencoded"})

    if "credentials" in flask.session:
        del flask.session["credentials"]
        del flask.session["username"]

    status_code = getattr(revoke, "status_code")
    if status_code == 200:
        return flask.render_template("authorization.html")
    else:
        return flask.render_template(
            "index.html", message="An error occurred during revocation!")

Java

सेवा क्लास में कोई ऐसा तरीका जोड़ें जो निरस्त एंडपॉइंट को कॉल करता है.

/** Revokes the app's permissions to the user's account.
*   @param credentials retrieved from the authorization flow.
*   @return response entity returned from the HTTP call to obtain response
*   information.
*   @throws RestClientException if the POST request to the revoke endpoint is
*   unsuccessful.
*/
public ResponseEntity<String> revokeCredentials(Credential credentials) throws RestClientException {
    try {
        String accessToken = credentials.getAccessToken();
        String url = "https://oauth2.googleapis.com/revoke?token=" + accessToken;

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(httpHeaders);
        ResponseEntity<String> responseEntity = new RestTemplate().exchange(
            url,
            HttpMethod.POST,
            httpEntity,
            String.class);
        return responseEntity;
    } catch (RestClientException e) {
        throw e;
    }
}

उस कंट्रोलर में, /revoke एंडपॉइंट जोड़ें जो सेशन को हटा दे और रद्द करने की प्रोसेस पूरी होने पर, उपयोगकर्ता को अनुमति वाले पेज पर रीडायरेक्ट कर दे.

/** Revokes the app's permissions and returns the authorization page.
*   @param session the current session.
*   @return the authorization page.
*   @throws Exception if revoking access is unsuccessful.
*/
@GetMapping(value = {"/revoke"})
public String revoke(HttpSession session) throws Exception {
    try {
        if (session != null && session.getAttribute("credentials") != null) {
            Credential credentials = (Credential) session.getAttribute("credentials");
            ResponseEntity responseEntity = authService.revokeCredentials(credentials);
            Integer httpStatusCode = responseEntity.getStatusCodeValue();

            if (httpStatusCode != 200) {
                return onError("There was an issue revoking access: " +
                    responseEntity.getStatusCode(), model);
            }
            session.removeAttribute("credentials");
        }
        return startAuthFlow(model);
    } catch (Exception e) {
        return onError(e.getMessage(), model);
    }
}

ऐड-ऑन को आज़माएं

Google Classroom में, Teacher टेस्ट उपयोगकर्ता के तौर पर साइन इन करें. क्लासवर्क टैब पर जाएं और नया असाइनमेंट बनाएं. टेक्स्ट एरिया के नीचे ऐड-ऑन बटन पर क्लिक करें. इसके बाद, अपना ऐड-ऑन चुनें. इससे iframe खुल जाएगा और ऐड-ऑन उस अटैचमेंट सेटअप यूआरआई को लोड करता है जिसे आपने GWM SDK के ऐप्लिकेशन कॉन्फ़िगरेशन पेज में बताया है.

बधाई हो! आप अगले चरण पर जाने के लिए तैयार हैं: अपने ऐड-ऑन पर बार-बार विज़िट किए जाने को मैनेज करना.