![post-title](https://i.ytimg.com/vi/_RsaNzZFuUU/hqdefault.jpg)
django view redirect 在 コバにゃんチャンネル Youtube 的最讚貼文
![post-title](https://i.ytimg.com/vi/_RsaNzZFuUU/hqdefault.jpg)
Severity: Notice
Message: Trying to get property 'plaintext' of non-object
Filename: models/Crawler_model.php
Line Number: 228
Backtrace:
File: /var/www/html/KOL/voice/application/models/Crawler_model.php
Line: 228
Function: _error_handler
File: /var/www/html/KOL/voice/application/controllers/Pages.php
Line: 336
Function: get_dev_google_article
File: /var/www/html/KOL/voice/public/index.php
Line: 319
Function: require_once
Severity: Notice
Message: Trying to get property 'plaintext' of non-object
Filename: models/Crawler_model.php
Line Number: 229
Backtrace:
File: /var/www/html/KOL/voice/application/models/Crawler_model.php
Line: 229
Function: _error_handler
File: /var/www/html/KOL/voice/application/controllers/Pages.php
Line: 336
Function: get_dev_google_article
File: /var/www/html/KOL/voice/public/index.php
Line: 319
Function: require_once
Search
This document explains how web server applications use Google API Client Libraries or Google
OAuth 2.0 endpoints to implement OAuth 2.0 authorization to access
the YouTube Data API.
OAuth 2.0 allows users to share specific data with an application while keeping their
usernames, passwords, and other information private.
For example, an application can use OAuth 2.0 to obtain permission
to upload videos to a user's YouTube channel.
This OAuth 2.0 flow is specifically for user authorization. It is designed for applications
that can store confidential information and maintain state. A properly authorized web server
application can access an API while the user interacts with the application or after the user
has left the application.
Web server applications frequently also use
service accounts to authorize API requests, particularly when calling Cloud APIs to access
project-based data rather than user-specific data. Web server applications can use service
accounts in conjunction with user authorization.
Note that the YouTube Data API supports the service account flow only for
YouTube content owners that own and manage multiple YouTube channels.
Specifically, content owners can use service accounts to call API methods that
support the onBehalfOfContentOwner
request parameter.
The language-specific examples on this page use
Google API Client Libraries to implement
OAuth 2.0 authorization. To run the code samples, you must first install the
client library for your language.
When you use a Google API Client Library to handle your application's OAuth 2.0 flow, the client
library performs many actions that the application would otherwise need to handle on its own. For
example, it determines when the application can use or refresh stored access tokens as well as
when the application must reacquire consent. The client library also generates correct redirect
URLs and helps to implement redirect handlers that exchange authorization codes for access tokens.
Google API Client Libraries for server-side applications are available for the following languages:
Any application that calls Google APIs needs to enable those APIs in the
API Console.
To enable an API for your project:
Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials
that identify the application to Google's OAuth 2.0 server. The following steps explain how to
create credentials for your project. Your applications can then use the credentials to access APIs
that you have enabled for that project.
For testing, you can specify URIs that refer to the local machine, such as
http://localhost:8080
. With that in mind, please note that all of the
examples in this document use http://localhost:8080
as the redirect URI.
We recommend that you design your app's auth endpoints so
that your application does not expose authorization codes to other resources on the
page.
After creating your credentials, download the client_secret.json file from the
API Console. Securely store the file in a location that only
your application can access.
Scopes enable your application to only request access to the resources that it needs while also
enabling users to control the amount of access that they grant to your application. Thus, there
may be an inverse relationship between the number of scopes requested and the likelihood of
obtaining user consent.
Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes
that your app will need permission to access.
We also recommend that your application request access to authorization scopes via an
incremental authorization process, in which your application
requests access to user data in context. This best practice helps users to more easily understand
why your application needs the access it is requesting.
The YouTube Data API v3 uses the following scopes:
The OAuth 2.0 API Scopes document contains a full
list of scopes that you might use to access Google APIs.
To run any of the code samples in this document, you'll need a Google account, access to the
Internet, and a web browser. If you are using one of the API client libraries, also see the
language-specific requirements below.
To run the PHP code samples in this document, you'll need:
The Google APIs Client Library for PHP:
composer require google/apiclient:^2.15.0
See Google APIs Client Library for
PHP for more information.
To run the Python code samples in this document, you'll need:
pip install --upgrade google-api-python-client
google-auth
, google-auth-oauthlib
, andgoogle-auth-httplib2
for user authorization.
pip install --upgrade google-auth google-auth-oauthlib google-auth-httplib2
pip install --upgrade flask
requests
HTTP library.
pip install --upgrade requests
Review the Google API Python client library
release note
if you aren't able to upgrade python and associated migration guide.
To run the Ruby code samples in this document, you'll need:
The Google Auth Library for Ruby:
gem install googleauth
The Sinatra Ruby web application framework.
gem install sinatra
To run the Node.js code samples in this document, you'll need:
The Google APIs Node.js Client:
npm install googleapis crypto express express-session
You do not need to install any libraries to be able to directly call the OAuth 2.0
endpoints.
The following steps show how your application interacts with Google's OAuth 2.0 server to obtain
a user's consent to perform an API request on the user's behalf. Your application must have that
consent before it can execute a Google API request that requires user authorization.
The list below quickly summarizes these steps:
Your first step is to create the authorization request. That request sets parameters that
identify your application and define the permissions that the user will be asked to grant to
your application.
The tabs below define the supported authorization parameters for web server applications. The
language-specific examples also show how to use a client library or authorization library to
configure an object that sets those parameters.
The following code snippet creates a Google\Client()
object, which defines the
parameters in the authorization request.
That object uses information from your client_secret.json file to identify your
application. (See creating authorization credentials for more about
that file.) The object also identifies the scopes that your application is requesting permission
to access and the URL to your application's auth endpoint, which will handle the response from
Google's OAuth 2.0 server. Finally, the code sets the optional access_type
and
include_granted_scopes
parameters.
For example, this code requests offline access to manage a user's YouTube
account:
use Google\Client;$client = new Client();// Required, call the setAuthConfig function to load authorization credentials fromPython
// client_secret.json file.
$client->setAuthConfig('client_secret.json');// Required, to set the scope value, call the addScope function
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);// Required, call the setRedirectUri function to specify a valid redirect URI for the
// provided client_id
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php');// Recommended, offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType('offline');// Recommended, call the setState function. Using a state value can increase your assurance that
// an incoming connection is the result of an authentication request.
$client->setState($sample_passthrough_value);// Optional, if your application knows which user is trying to authenticate, it can use this
// parameter to provide a hint to the Google Authentication Server.
$client->setLoginHint('hint@example.com');// Optional, call the setPrompt function to set "consent" will prompt the user for consent
$client->setPrompt('consent');// Optional, call the setIncludeGrantedScopes function with true to enable incremental
// authorization
$client->setIncludeGrantedScopes(true);
The following code snippet uses the google-auth-oauthlib.flow
module to construct
the authorization request.
The code constructs a Flow
object, which identifies your application using
information from the client_secret.json file that you downloaded after
creating authorization credentials. That object also identifies the
scopes that your application is requesting permission to access and the URL to your application's
auth endpoint, which will handle the response from Google's OAuth 2.0 server. Finally, the code
sets the optional access_type
and include_granted_scopes
parameters.
For example, this code requests offline access to manage a user's YouTube
account:
import google.oauth2.credentialsRuby
import google_auth_oauthlib.flow# Required, call the from_client_secrets_file method to retrieve the client ID from a
# client_secret.json file. The client ID (from that file) and access scopes are required. (You can
# also use the from_client_config method, which passes the client configuration as it originally
# appeared in a client secrets file but doesn't access the file itself.)
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_secret.json',
scopes=['https://www.googleapis.com/auth/youtube.force-ssl'])# Required, indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value 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 = 'https://www.example.com/oauth2callback'# Generate URL for request to Google's OAuth 2.0 server.
# Use kwargs to set optional request parameters.
authorization_url, state = flow.authorization_url(
# Recommended, 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',
# Optional, enable incremental authorization. Recommended as a best practice.
include_granted_scopes='true',
# Optional, if your application knows which user is trying to authenticate, it can use this
# parameter to provide a hint to the Google Authentication Server.
login_hint='hint@example.com',
# Optional, set prompt to 'consent' will prompt the user for consent
prompt='consent')
Use the client_secrets.json file that you created to configure a client object in your
application. When you configure a client object, you specify the scopes your application needs to
access, along with the URL to your application's auth endpoint, which will handle the response
from the OAuth 2.0 server.
For example, this code requests offline access to manage a user's YouTube
account:
require 'googleauth'
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'require 'google/apis/youtube_v3'# Required, call the from_file method to retrieve the client ID from a
# client_secret.json file.
client_id = Google::Auth::ClientId.from_file('/path/to/client_secret.json')# Required, scope value
scope = 'https://www.googleapis.com/auth/youtube.force-ssl'# Required, Authorizers require a storage instance to manage long term persistence of
# access and refresh tokens.
token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new)# Required, indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value 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.
callback_uri = '/oauth2callback'# To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
# from the client_secret.json file. To get these credentials for your application, visit
# https://console.cloud.google.com/apis/credentials.
authorizer = Google::Auth::WebUserAuthorizer.new(client_id, scope,
token_store, callback_uri)
Your application uses the client object to perform OAuth 2.0 operations, such as generating
authorization request URLs and applying access tokens to HTTP requests.
The following code snippet creates a google.auth.OAuth2
object, which defines the
parameters in the authorization request.
That object uses information from your client_secret.json file to identify your application. To
ask for permissions from a user to retrieve an access token, you redirect them to a consent page.
To create a consent page URL:
const {google} = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');/**
* To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
* from the client_secret.json file. To get these credentials for your application, visit
* https://console.cloud.google.com/apis/credentials.
*/
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);// Access scopes for YouTube API
const scopes = [
'https://www.googleapis.com/auth/youtube.force-ssl'
];// Generate a secure random state value.
const state = crypto.randomBytes(32).toString('hex');// Store state in the session
req.session.state = state;// Generate a url that asks permissions for the Drive activity and Google Calendar scope
const authorizationUrl = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
/** Pass in the scopes array defined above.
* Alternatively, if only one scope is needed, you can pass a scope URL as a string */
scope: scopes,
// Enable incremental authorization. Recommended as a best practice.
include_granted_scopes: true,
// Include the state parameter to reduce the risk of CSRF attacks.
state: state
});
Important Note - The refresh_token
is only returned on the first
authorization. More details
here.
Google's OAuth 2.0 endpoint is at https://accounts.google.com/o/oauth2/v2/auth
. This
endpoint is accessible only over HTTPS. Plain HTTP connections are refused.
The Google authorization server supports the following query string parameters for web
server applications:
client_id
The client ID for your application. You can find this value in the
Cloud Console
Clients page.
redirect_uri
Determines where the API server redirects the user after the user completes the
authorization flow. The value must exactly match one of the authorized redirect URIs for
the OAuth 2.0 client, which you configured in your client's
Cloud Console
Clients page. If this value doesn't match an
authorized redirect URI for the provided client_id
you will get a
redirect_uri_mismatch
error.
Note that the http
or https
scheme, case, and trailing slash
('/
') must all match.
response_type
Determines whether the Google OAuth 2.0 endpoint returns an authorization code.
Set the parameter value to code
for web server applications.
scope
A
space-delimited
list of scopes that identify the resources that your application could access on the
user's behalf. These values inform the consent screen that Google displays to the
user.
Scopes enable your application to only request access to the resources that it needs
while also enabling users to control the amount of access that they grant to your
application. Thus, there is an inverse relationship between the number of scopes requested
and the likelihood of obtaining user consent.
The YouTube Data API v3 uses the following scopes:
The OAuth 2.0 API Scopes document provides
a full list of scopes that you might use to access Google APIs.
We recommend that your application request access to authorization scopes in context
whenever possible. By requesting access to user data in context, via
incremental authorization, you help users to more easily
understand why your application needs the access it is requesting.
access_type
Indicates whether your application can refresh access tokens when the user is not present
at the browser. Valid parameter values are online
, which is the default
value, and offline
.
Set the value to offline
if your application needs to refresh access tokens
when the user is not present at the browser. This is the method of refreshing access
tokens described later in this document. This value instructs the Google authorization
server to return a refresh token and an access token the first time that your
application exchanges an authorization code for tokens.
state
Specifies any string value that your application uses to maintain state between your
authorization request and the authorization server's response.
The server returns the exact value that you send as a name=value
pair in the
URL query component (?
) of the
redirect_uri
after the user consents to or denies your application's
access request.
You can use this parameter for several purposes, such as directing the user to the
correct resource in your application, sending nonces, and mitigating cross-site request
forgery. Since your redirect_uri
can be guessed, using a state
value can increase your assurance that an incoming connection is the result of an
authentication request. If you generate a random string or encode the hash of a cookie or
another value that captures the client's state, you can validate the response to
additionally ensure that the request and response originated in the same browser,
providing protection against attacks such as
cross-site request
forgery. See the
OpenID Connect
documentation for an example of how to create and confirm a state
token.
state
parameter to maintaininclude_granted_scopes
Enables applications to use incremental authorization to request access to additional
scopes in context. If you set this parameter's value to true
and the
authorization request is granted, then the new access token will also cover any scopes to
which the user previously granted the application access. See the
incremental authorization section for examples.
enable_granular_consent
Defaults to true
. If set to false
,
more
granular Google Account permissions
will be disabled for OAuth client IDs created before 2019. No effect for newer
OAuth client IDs, since more granular permissions is always enabled for them.
When Google enables granular permissions for an application, this parameter will no
longer have any effect.
login_hint
If your application knows which user is trying to authenticate, it can use this parameter
to provide a hint to the Google Authentication Server. The server uses the hint to
simplify the login flow either by prefilling the email field in the sign-in form or by
selecting the appropriate multi-login session.
Set the parameter value to an email address or sub
identifier, which is
equivalent to the user's Google ID.
prompt
A space-delimited, case-sensitive list of prompts to present the user. If you don't
specify this parameter, the user will be prompted only the first time your project
requests access. See
Prompting re-consent for more information.
Possible values are:
none
consent
select_account
Redirect the user to Google's OAuth 2.0 server to initiate the authentication and
authorization process. Typically, this occurs when your application first needs to access the
user's data. In the case of incremental authorization, this
step also occurs when your application first needs to access additional resources that it does
not yet have permission to access.
$auth_url = $client->createAuthUrl();
$auth_url
:header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
This example shows how to redirect the user to the authorization URL using the Flask web
application framework:
return flask.redirect(authorization_url)Ruby
auth_uri = authorizer.get_authorization_url(request: request)
auth_uri
.authorizationUrl
from Step 1generateAuthUrl
method to request access from Google's OAuth 2.0 server.authorizationUrl
.res.redirect(authorizationUrl);
The sample URL below requests offline access
(access_type=offline
) to a scope that permits access to view
the user's YouTube account. It uses incremental authorization to ensure that
the new access token covers any scopes to which the user previously granted
the application access. The URL also sets values for the required
redirect_uri
, response_type
, and
client_id
parameters as well as for the state
parameter. The URL contains line breaks and spaces for readability.
https://accounts.google.com/o/oauth2/v2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
access_type=offline&
include_granted_scopes=true&
state=state_parameter_passthrough_value&
redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
response_type=code&
client_id=client_id
After you create the request URL, redirect the user to it.
Google's OAuth 2.0 server authenticates the user and obtains consent from the user for your
application to access the requested scopes. The response is sent back to your application
using the redirect URL you specified.
In this step, the user decides whether to grant your application the requested access. At this
stage, Google displays a consent window that shows the name of your application and the Google API
services that it is requesting permission to access with the user's authorization credentials and
a summary of the scopes of access to be granted. The
user can then consent to grant access to one or more scopes requested by your application or
refuse the request.
Your application doesn't need to do anything at this stage as it waits for the response from
Google's OAuth 2.0 server indicating whether any access was granted. That response is explained in
the following step.
Requests to Google's OAuth 2.0 authorization endpoint may display user-facing error messages
instead of the expected authentication and authorization flows. Common error codes and suggested
resolutions are listed below.
admin_policy_enforced
The Google Account is unable to authorize one or more scopes requested due to the policies of
their Google Workspace administrator. See the Google Workspace Admin help article
Control which third-party & internal apps access Google Workspace data
for more information about how an administrator may restrict access to all scopes or sensitive and
restricted scopes until access is explicitly granted to your OAuth client ID.
disallowed_useragent
The authorization endpoint is displayed inside an embedded user-agent disallowed by Google's
OAuth 2.0 Policies.
Android developers may encounter this error message when opening authorization requests in
android.webkit.WebView
.
Developers should instead use Android libraries such as
Google Sign-In for Android or OpenID Foundation's
AppAuth for Android.
Web developers may encounter this error when an Android app opens a general web link in an
embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from
your site. Developers should allow general links to open in the default link handler of the
operating system, which includes both
Android App Links
handlers or the default browser app. The
Android Custom Tabs
library is also a supported option.
iOS and macOS developers may encounter this error when opening authorization requests in
WKWebView
.
Developers should instead use iOS libraries such as
Google Sign-In for iOS or OpenID Foundation's
AppAuth for iOS.
Web developers may encounter this error when an iOS or macOS app opens a general web link in
an embedded user-agent and a user navigates to Google's OAuth 2.0 authorization endpoint from
your site. Developers should allow general links to open in the default link handler of the
operating system, which includes both
Universal Links
handlers or the default browser app. The
SFSafariViewController
library is also a supported option.
org_internal
The OAuth client ID in the request is part of a project limiting access to Google Accounts in a
specific
Google Cloud Organization.
For more information about this configuration option see the
User type
section in the Setting up your OAuth consent screen help article.
invalid_client
The OAuth client secret is incorrect. Review the
OAuth client
configuration, including the client ID and secret used for this request.
invalid_grant
When refreshing an access token or using
incremental authorization, the token may have expired or has
been invalidated.
Authenticate the user again and ask for user consent to obtain new tokens. If you are continuing
to see this error, ensure that your application has been configured correctly and that you are
using the correct tokens and parameters in your request. Otherwise, the user account may have
been deleted or disabled.
redirect_uri_mismatch
The redirect_uri
passed in the authorization request does not match an authorized
redirect URI for the OAuth client ID. Review authorized redirect URIs in the
Google Cloud Console
Clients page.
The redirect_uri
parameter may refer to the OAuth out-of-band (OOB) flow that has
been deprecated and is no longer supported. Refer to the
migration guide to update your
integration.
invalid_request
There was something wrong with the request you made. This could be due to a number of reasons:
state
received from Google matches the state
sent in theThe OAuth 2.0 server responds to your application's access request by using the URL specified
in the request.
If the user approves the access request, then the response contains an authorization code. If
the user does not approve the request, the response contains an error message. The
authorization code or error message that is returned to the web server appears on the query
string, as shown below:
An error response:
https://oauth2.example.com/auth?error=access_denied
An authorization code response:
Important: If your response endpoint renders an
https://oauth2.example.com/auth?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7
Referer
HTTP header may beCarefully consider whether you want to send authorization credentials to all resources on
that page (especially third-party scripts such as social plugins and analytics). To avoid
this issue, we recommend that the server first handle the request, then redirect to another
URL that doesn't include the response parameters.
You can test this flow by clicking on the following sample URL, which requests
read-only access to view metadata for files in your Google Drive and read-only
access to view your Google Calendar events:
https://accounts.google.com/o/oauth2/v2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyoutube.readonly&
access_type=offline&
include_granted_scopes=true&
state=state_parameter_passthrough_value&
redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
response_type=code&
client_id=client_id
After completing the OAuth 2.0 flow, you should be redirected to
http://localhost/oauth2callback
, which will likely yield a
404 NOT FOUND
error unless your local machine serves a file at that address. The
next step provides more detail about the information returned in the URI when the user is
redirected back to your application.
After the web server receives the authorization code, it can exchange the authorization code
for an access token.
To exchange an authorization code for an access token, use the
fetchAccessTokenWithAuthCode
method:
$access_token = $client->fetchAccessTokenWithAuthCode($_GET['code']);
Python On your callback page, use the google-auth
library to verify the authorization
server response. Then, use the flow.fetch_token
method to exchange the authorization
code in that response for an access token:
state = flask.session['state']Ruby
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
'client_secret.json',
scopes=['https://www.googleapis.com/auth/youtube.force-ssl'],
state=state)
flow.redirect_uri = flask.url_for('oauth2callback', _external=True)authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response)# Store the credentials in the session.
# ACTION ITEM for developers:
# Store user's access and refresh tokens in your data store if
# incorporating this code into your real app.
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,
'granted_scopes': credentials.granted_scopes}
On your callback page, use the googleauth
library to verify the authorization server
response. Use the authorizer.handle_auth_callback_deferred
method to save the
authorization code and redirect back to the URL that originally requested authorization. This
defers the exchange of the code by temporarily stashing the results in the user's session.
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)Node.js
redirect target_url
To exchange an authorization code for an access token, use the getToken
method:
const url = require('url');// Receive the callback from Google's OAuth 2.0 server.HTTP/REST
app.get('/oauth2callback', async (req, res) => {
let q = url.parse(req.url, true).query; if (q.error) { // An error response e.g. error=access_denied
console.log('Error:' + q.error);
} else if (q.state !== req.session.state) { //check state value
console.log('State mismatch. Possible CSRF attack');
res.end('State mismatch. Possible CSRF attack');
} else { // Get access and refresh tokens (if access_type is offline) let { tokens } = await oauth2Client.getToken(q.code);
oauth2Client.setCredentials(tokens);
});
To exchange an authorization code for an access token, call the
https://oauth2.googleapis.com/token
endpoint and set the following parameters:
client_id
client_secret
code
grant_type
authorization_code
.redirect_uri
client_id
.The following snippet shows a sample request:
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencodedcode=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=https%3A//oauth2.example.com/code&
grant_type=authorization_code
Google responds to this request by returning a JSON object that contains a short-lived access
token and a refresh token. Note that the refresh token is only returned if your application set the access_type
parameter to offline
in the initial request to Google's
authorization server.
The response contains the following fields:
access_token
expires_in
refresh_token
access_type
offline
in the initial request to Google's authorization server.scope
access_token
expressed as a list oftoken_type
Bearer
.The following snippet shows a sample response:
{Note: Your application should ignore any unrecognized fields included in
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"token_type": "Bearer",
"scope": "https://www.googleapis.com/auth/youtube.force-ssl",
"refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
When exchanging the authorization code for an access token you may encounter the following
error instead of the expected response. Common error codes and suggested resolutions are
listed below.
invalid_grant
The supplied authorization code is invalid or in the wrong format. Request a new code by
restarting the OAuth process to prompt the user for consent
again.
When requesting multiple scopes at once, users may not grant all scopes your app
requests. Your app should always check which scopes were granted by the user and handle
any denial of scopes by disabling relevant features. Review
How to handle granular permissions
for more information.
To check which scopes the user has granted, use the getGrantedScope()
method:
// Space-separated string of granted scopes if it exists, otherwise null.Python
$granted_scopes = $client->getOAuth2Service()->getGrantedScope();
The returned credentials
object has a granted_scopes
property,
which is a list of scopes the user has granted to your app.
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,
'granted_scopes': credentials.granted_scopes}
When requesting multiple scopes at once, check which scopes were granted through
the scope
property of the credentials
object.
# User authorized the request. Now, check which scopes were granted.Node.js
if credentials.scope.include?(Google::Apis::YoutubeV3::AUTH_YOUTUBE_FORCE_SSL)
# User authorized permission to see, edit, and permanently delete the
# YouTube videos, ratings, comments and captions.
# Calling the APIs, etc
else
# User didn't authorize the permission.
# Update UX and application accordingly
end
When requesting multiple scopes at once, check which scopes were granted through
the scope
property of the tokens
object.
// User authorized the request. Now, check which scopes were granted.HTTP/REST
if (tokens.scope.includes('https://www.googleapis.com/auth/youtube.force-ssl'))
{
// User authorized permission to see, edit, and permanently delete the
// YouTube videos, ratings, comments and captions.
// Calling the APIs, etc.
}
else
{
// User didn't authorize read-only Drive activity permission.
// Update UX and application accordingly
}
To check whether the user has granted your application access to a particular scope,
exam the scope
field in the access token response. The scopes of access granted by
the access_token expressed as a list of space-delimited, case-sensitive strings.
For example, the following sample access token response indicates that the user has granted your
application permission to see, edit, and permanently delete user's YouTube videos, ratings,
comments and captions:
{
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"token_type": "Bearer",
"scope": "https://www.googleapis.com/auth/youtube.force-ssl",
"refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}
Use the access token to call Google APIs by completing the following steps:
Google\Client
object — forsetAccessToken
method: $client->setAccessToken($access_token);
Google\Client
object to the constructor for the API you$youtube = new Google_Service_YouTube($client);
$channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
After obtaining an access token, your application can use that token to authorize API requests on
behalf of a given user account or service account. Use the user-specific authorization credentials
to build a service object for the API that you want to call, and then use that object to make
authorized API requests.
googleapiclient.discovery
library's build
method with thefrom googleapiclient.discovery import buildyoutube = build('youtube', 'v3', credentials=credentials)
channel = youtube.channels().list(mine=True, part='snippet').execute()
After obtaining an access token, your application can use that token to make API requests on
behalf of a given user account or service account. Use the user-specific authorization credentials
to build a service object for the API that you want to call, and then use that object to make
authorized API requests.
youtube = Google::Apis::YoutubeV3::YouTubeService.new
youtube.authorization = credentials
channel = youtube.list_channels(part, :mine => mine)
Alternately, authorization can be provided on a per-method basis by supplying the
options
parameter to a method:
channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })
After obtaining an access token and setting it to the OAuth2
object, use the object
to call Google APIs. Your application can use that token to authorize API requests on behalf of
a given user account or service account. Build a service object for the API that you want to call.
For example, the following code uses the Google Drive API to list filenames in the user's Drive.
const { google } = require('googleapis');// Example of using YouTube API to list channels.HTTP/REST
var service = google.youtube('v3');
service.channels.list({
auth: oauth2Client,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
After your application obtains an access token, you can use the token to make calls to a Google
API on behalf of a given
user account if the scope(s) of access required by the API have been granted. To do this, include
the access token in a request to the API by including either an access_token
query
parameter or an Authorization
HTTP header Bearer
value. When possible,
the HTTP header is preferable, because query strings tend to be visible in server logs. In most
cases you can use a client library to set up your calls to Google APIs (for example, when
calling the YouTube Data API).
Note that the YouTube Data API supports service accounts only for YouTube
content owners that own and manage multiple YouTube channels, such as record
labels and movie studios.
You can try out all the Google APIs and view their scopes at the
OAuth 2.0 Playground.
A call to the
youtube.channels
endpoint (the YouTube Data API) using the Authorization: Bearer
HTTP
header might look like the following. Note that you need to specify your own access token:
GET /youtube/v3/channels?part=snippet&mine=true HTTP/1.1
Host: www.googleapis.com
Authorization: Bearer access_token
Here is a call to the same API for the authenticated user using the access_token
query string parameter:
GET https://www.googleapis.com/youtube/v3/channels?access_token=access_token&part=snippet&mine=true
curl
examplesYou can test these commands with the curl
command-line application. Here's an
example that uses the HTTP header option (preferred):
curl -H "Authorization: Bearer access_token" https://www.googleapis.com/youtube/v3/channels?part=snippet&mine=true
Or, alternatively, the query string parameter option:
curl https://www.googleapis.com/youtube/v3/channels?access_token=access_token&part=snippet&mine=true
The following example prints a JSON-formatted object showing information
about a user's YouTube channel after the user authenticates and authorizes the
application to manage the user's YouTube account.
To run this example:
http://localhost:8080
.
mkdir ~/php-oauth2-example
cd ~/php-oauth2-example
composer require google/apiclient:^2.15.0
index.php
and oauth2callback.php
with the
php -S localhost:8080 ~/php-oauth2-example
<?phpoauth2callback.php
require_once __DIR__.'/vendor/autoload.php';session_start();$client = new Google\Client();
$client->setAuthConfig('client_secret.json');// User granted permission as an access token is in the session.
if (isset($_SESSION['access_token']) && $_SESSION['access_token'])
{
$client->setAccessToken($_SESSION['access_token']);
$youtube = new Google_Service_YouTube($client);
$channel = $youtube->channels->listChannels('snippet', array('mine' => $mine));
echo json_encode($channel);
}
else
{
// Redirect users to outh2call.php which redirects users to Google OAuth 2.0
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/oauth2callback.php';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}
?>
<?phpPython
require_once __DIR__.'/vendor/autoload.php';session_start();$client = new Google\Client();// Required, call the setAuthConfig function to load authorization credentials from
// client_secret.json file.
$client->setAuthConfigFile('client_secret.json');
$client->setRedirectUri('http://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);// Required, to set the scope value, call the addScope function.
$client->addScope(GOOGLE_SERVICE_YOUTUBE::YOUTUBE_FORCE_SSL);// Enable incremental authorization. Recommended as a best practice.
$client->setIncludeGrantedScopes(true);// Recommended, offline access will give you both an access and refresh token so that
// your app can refresh the access token without user interaction.
$client->setAccessType("offline");// Generate a URL for authorization as it doesn't contain code and error
if (!isset($_GET['code']) && !isset($_GET['error']))
{
// Generate and set state value
$state = bin2hex(random_bytes(16));
$client->setState($state);
$_SESSION['state'] = $state; // Generate a url that asks permissions.
$auth_url = $client->createAuthUrl();
header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL));
}// User authorized the request and authorization code is returned to exchange access and
// refresh tokens.
if (isset($_GET['code']))
{
// Check the state value
if (!isset($_GET['state']) || $_GET['state'] !== $_SESSION['state']) {
die('State mismatch. Possible CSRF attack.');
} // Get access and refresh tokens (if access_type is offline)
$token = $client->fetchAccessTokenWithAuthCode($_GET['code']); /** Save access and refresh token to the session variables.
* ACTION ITEM: In a production app, you likely want to save the
* refresh token in a secure persistent storage instead. */
$_SESSION['access_token'] = $token;
$_SESSION['refresh_token'] = $client->getRefreshToken();
$redirect_uri = 'http://' . $_SERVER['HTTP_HOST'] . '/';
header('Location: ' . filter_var($redirect_uri, FILTER_SANITIZE_URL));
}// An error response e.g. error=access_denied
if (isset($_GET['error']))
{
echo "Error: ". $_GET['error'];
}
?>
This example uses the Flask framework. It
runs a web application at http://localhost:8080
that lets you test the OAuth 2.0
flow. If you go to that URL, you should see five links:
http://localhost:8080
as a valid redirect URI for your credentials and downloading# -*- coding: utf-8 -*-import osRuby
import flask
import requestsimport google.oauth2.credentials
import google_auth_oauthlib.flow
import googleapiclient.discovery# This variable specifies the name of a file that contains the OAuth 2.0
# information for this application, including its client_id and client_secret.
CLIENT_SECRETS_FILE = "client_secret.json"# The OAuth 2.0 access scope allows for access to the
# authenticated user's account and requires requests to use an SSL connection.
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'app = flask.Flask(__name__)
# Note: A secret key is included in the sample so that it works.
# If you use this code in your application, replace this with a truly secret
# key. See https://flask.palletsprojects.com/quickstart/#sessions.
app.secret_key = 'REPLACE ME - this value is here as a placeholder.'@app.route('/')
def index():
return print_index_table()@app.route('/test')
def test_api_request():
if 'credentials' not in flask.session:
return flask.redirect('authorize') # Load credentials from the session.
credentials = google.oauth2.credentials.Credentials(
**flask.session['credentials']) youtube = googleapiclient.discovery.build(
API_SERVICE_NAME, API_VERSION, credentials=credentials) channel = youtube.channels().list(mine=True, part='snippet').execute() # Save credentials back to session in case access token was refreshed.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
flask.session['credentials'] = credentials_to_dict(credentials) return flask.jsonify(**channel)
@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) # 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('oauth2callback', _external=True) 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 return flask.redirect(authorization_url)@app.route('/oauth2callback')
def oauth2callback():
# Specify the state when creating the flow in the callback so that it can
# verified in the authorization server response.
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('oauth2callback', _external=True) # Use the authorization server's response to fetch the OAuth 2.0 tokens.
authorization_response = flask.request.url
flow.fetch_token(authorization_response=authorization_response) # Store credentials in the session.
# ACTION ITEM: In a production app, you likely want to save these
# credentials in a persistent database instead.
credentials = flow.credentials
flask.session['credentials'] = credentials_to_dict(credentials) return flask.redirect(flask.url_for('test_api_request'))
@app.route('/revoke')
def revoke():
if 'credentials' not in flask.session:
return ('You need to <a href="/authorize">authorize</a> before ' +
'testing the code 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'}) status_code = getattr(revoke, 'status_code')
if status_code == 200:
return('Credentials successfully revoked.' + print_index_table())
else:
return('An error occurred.' + print_index_table())@app.route('/clear')
def clear_credentials():
if 'credentials' in flask.session:
del flask.session['credentials']
return ('Credentials have been cleared.<br><br>' +
print_index_table())def credentials_to_dict(credentials):
return {'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': credentials.token_uri,
'client_id': credentials.client_id,
'client_secret': credentials.client_secret,
'granted_scopes': credentials.granted_scopes}def print_index_table():
return ('<table>' +
'<tr><td><a href="/test">Test an API request</a></td>' +
'<td>Submit an API request and see a formatted JSON response. ' +
' Go through the authorization flow if there are no stored ' +
' credentials for the user.</td></tr>' +
'<tr><td><a href="/authorize">Test the auth flow directly</a></td>' +
'<td>Go directly to the authorization flow. If there are stored ' +
' credentials, you still might not be prompted to reauthorize ' +
' the application.</td></tr>' +
'<tr><td><a href="/revoke">Revoke current credentials</a></td>' +
'<td>Revoke the access token associated with the current user ' +
' session. After revoking credentials, if you go to the test ' +
' page, you should see an <code>invalid_grant</code> error.' +
'</td></tr>' +
'<tr><td><a href="/clear">Clear Flask session credentials</a></td>' +
'<td>Clear the access token currently stored in the user session. ' +
' After clearing the token, if you <a href="/test">test the ' +
' API request</a> again, you should go back to the auth flow.' +
'</td></tr></table>')if __name__ == '__main__':
# When running locally, disable OAuthlib's HTTPs verification.
# ACTION ITEM for developers:
# When running in production *do not* leave this option enabled.
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # This disables the requested scopes and granted scopes check.
# If users only grant partial request, the warning would not be thrown.
os.environ['OAUTHLIB_RELAX_TOKEN_SCOPE'] = '1' # Specify a hostname and port that are set as a valid redirect URI
# for your API project in the Google API Console.
app.run('localhost', 8080, debug=True)
This example uses the Sinatra framework.
require 'googleauth'Node.js
require 'googleauth/web_user_authorizer'
require 'googleauth/stores/redis_token_store'require 'google/apis/youtube_v3'require 'sinatra'configure do
enable :sessions # Required, call the from_file method to retrieve the client ID from a
# client_secret.json file.
set :client_id, Google::Auth::ClientId.from_file('/path/to/client_secret.json') # Required, scope value
# Access scopes for retrieving data about the user's YouTube channel.
scope = 'Google::Apis::YoutubeV3::AUTH_YOUTUBE_FORCE_SSL' # Required, Authorizers require a storage instance to manage long term persistence of
# access and refresh tokens.
set :token_store, Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) # Required, indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value 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.
set :callback_uri, '/oauth2callback' # To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI
# from the client_secret.json file. To get these credentials for your application, visit
# https://console.cloud.google.com/apis/credentials.
set :authorizer, Google::Auth::WebUserAuthorizer.new(settings.client_id, settings.scope,
settings.token_store, callback_uri: settings.callback_uri)
endget '/' do
# NOTE: Assumes the user is already authenticated to the app
user_id = request.session['user_id'] # Fetch stored credentials for the user from the given request session.
# nil if none present
credentials = settings.authorizer.get_credentials(user_id, request) if credentials.nil?
# Generate a url that asks the user to authorize requested scope(s).
# Then, redirect user to the url.
redirect settings.authorizer.get_authorization_url(request: request)
end
# User authorized read-only YouTube Data API permission.
# Example of using YouTube Data API to list user's YouTube channel
youtube = Google::Apis::YoutubeV3::YouTubeService.new
channel = youtube.list_channels(part, :mine => mine, options: { authorization: auth_client })
"<pre>#{JSON.pretty_generate(channel.to_h)}</pre>"
end# Receive the callback from Google's OAuth 2.0 server.
get '/oauth2callback' do
# Handle the result of the oauth callback. Defers the exchange of the code by
# temporarily stashing the results in the user's session.
target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred(request)
redirect target_url
end
To run this example:
http://localhost
.
mkdir ~/nodejs-oauth2-example
cd ~/nodejs-oauth2-example
npm install googleapis
main.js
with the following content.node .\main.js
const http = require('http');HTTP/REST
const https = require('https');
const url = require('url');
const { google } = require('googleapis');
const crypto = require('crypto');
const express = require('express');
const session = require('express-session');/**
* To use OAuth2 authentication, we need access to a CLIENT_ID, CLIENT_SECRET, AND REDIRECT_URI.
* To get these credentials for your application, visit
* https://console.cloud.google.com/apis/credentials.
*/
const oauth2Client = new google.auth.OAuth2(
YOUR_CLIENT_ID,
YOUR_CLIENT_SECRET,
YOUR_REDIRECT_URL
);// Access scopes for YouTube API
const scopes = [
'https://www.googleapis.com/auth/youtube.force-ssl'
];/* Global variable that stores user credential in this code example.
* ACTION ITEM for developers:
* Store user's refresh token in your data store if
* incorporating this code into your real app.
* For more information on handling refresh tokens,
* see https://github.com/googleapis/google-api-nodejs-client#handling-refresh-tokens
*/
let userCredential = null;async function main() {
const app = express(); app.use(session({
secret: 'your_secure_secret_key', // Replace with a strong secret
resave: false,
saveUninitialized: false,
})); // Example on redirecting user to Google's OAuth 2.0 server.
app.get('/', async (req, res) => {
// Generate a secure random state value.
const state = crypto.randomBytes(32).toString('hex');
// Store state in the session
req.session.state = state; // Generate a url that asks permissions for the Drive activity and Google Calendar scope
const authorizationUrl = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
/** Pass in the scopes array defined above.
* Alternatively, if only one scope is needed, you can pass a scope URL as a string */
scope: scopes,
// Enable incremental authorization. Recommended as a best practice.
include_granted_scopes: true,
// Include the state parameter to reduce the risk of CSRF attacks.
state: state
}); res.redirect(authorizationUrl);
}); // Receive the callback from Google's OAuth 2.0 server.
app.get('/oauth2callback', async (req, res) => {
// Handle the OAuth 2.0 server response
let q = url.parse(req.url, true).query; if (q.error) { // An error response e.g. error=access_denied
console.log('Error:' + q.error);
} else if (q.state !== req.session.state) { //check state value
console.log('State mismatch. Possible CSRF attack');
res.end('State mismatch. Possible CSRF attack');
} else { // Get access and refresh tokens (if access_type is offline)
let { tokens } = await oauth2Client.getToken(q.code);
oauth2Client.setCredentials(tokens); /** Save credential to the global variable in case access token was refreshed.
* ACTION ITEM: In a production app, you likely want to save the refresh token
* in a secure persistent database instead. */
userCredential = tokens;
// Example of using YouTube API to list channels.
var service = google.youtube('v3');
service.channels.list({
auth: oauth2Client,
part: 'snippet,contentDetails,statistics',
forUsername: 'GoogleDevelopers'
}, function (err, response) {
if (err) {
console.log('The API returned an error: ' + err);
return;
}
var channels = response.data.items;
if (channels.length == 0) {
console.log('No channel found.');
} else {
console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
'it has %s views.',
channels[0].id,
channels[0].snippet.title,
channels[0].statistics.viewCount);
}
});
}
}); // Example on revoking a token
app.get('/revoke', async (req, res) => {
// Build the string for the POST request
let postData = "token=" + userCredential.access_token; // Options for POST request to Google's OAuth 2.0 server to revoke a token
let postOptions = {
host: 'oauth2.googleapis.com',
port: '443',
path: '/revoke',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
}; // Set up the request
const postReq = https.request(postOptions, function (res) {
res.setEncoding('utf8');
res.on('data', d => {
console.log('Response: ' + d);
});
}); postReq.on('error', error => {
console.log(error)
}); // Post the request with data
postReq.write(postData);
postReq.end();
});
const server = http.createServer(app);
server.listen(8080);
}
main().catch(console.error);
This Python example uses the Flask framework
and the Requests library to demonstrate the OAuth
2.0 web flow. We recommend using the Google API Client Library for Python for this flow. (The
example in the Python tab does use the client library.)
import json
import flask
import requestsapp = flask.Flask(__name__)# To get these credentials (CLIENT_ID CLIENT_SECRET) and for your application, visit
# https://console.cloud.google.com/apis/credentials.
CLIENT_ID = '123456789.apps.googleusercontent.com'
CLIENT_SECRET = 'abc123' # Read from a file or environmental variable in a real app# Access scopes for YouTube API
SCOPE = 'https://www.googleapis.com/auth/youtube.force-ssl'# Indicate where the API server will redirect the user after the user completes
# the authorization flow. The redirect URI is required. The value 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.
REDIRECT_URI = 'http://example.com/oauth2callback'@app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback')) credentials = json.loads(flask.session['credentials']) if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauth2callback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
req_uri = 'https://www.googleapis.com/youtube/v3/channels/list'
r = requests.get(req_uri, headers=headers)
return r.text @app.route('/oauth2callback')
def oauth2callback():
if 'code' not in flask.request.args:
state = str(uuid.uuid4())
flask.session['state'] = state
# Generate a url that asks permissions for the Drive activity
# and Google Calendar scope. Then, redirect user to the url.
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
'&client_id={}&redirect_uri={}&scope={}&state={}').format(CLIENT_ID, REDIRECT_URI,
SCOPE, state)
return flask.redirect(auth_uri)
else:
if 'state' not in flask.request.args or flask.request.args['state'] != flask.session['state']:
return 'State mismatch. Possible CSRF attack.', 400 auth_code = flask.request.args.get('code')
data = {'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'} # Exchange authorization code for access and refresh tokens (if access_type is offline)
r = requests.post('https://oauth2.googleapis.com/token', data=data)
flask.session['credentials'] = r.text
return flask.redirect(flask.url_for('index'))if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run()
Google applies the following validation rules to redirect URIs in order to help developers
keep their applications secure. Your redirect URIs must adhere to these rules. See
RFC 3986 section 3 for the
definition of domain, host, path, query, scheme and userinfo, mentioned below.
Redirect URIs must use the HTTPS scheme, not plain HTTP. Localhost URIs (including
localhost IP address URIs) are exempt from this rule.
Hosts cannot be raw IP addresses. Localhost IP addresses are exempted from this rule.
“googleusercontent.com”
.goo.gl
) unless“/google-callback/”
in its path or end with“/google-callback”
.Redirect URIs cannot contain the userinfo subcomponent.
Redirect URIs cannot contain a path traversal (also called directory backtracking),
which is represented by an “/..”
or “\..”
or their URL
encoding.
Redirect URIs cannot contain
open redirects.
Redirect URIs cannot contain the fragment component.
'*'
)%00
,%C0%80
)In the OAuth 2.0 protocol, your app requests authorization to access resources, which are
identified by scopes. It is considered a best user-experience practice to request authorization
for resources at the time you need them. To enable that practice, Google's authorization server
supports incremental authorization. This feature lets you request scopes as they are needed and,
if the user grants permission for the new scope, returns an authorization code that may be
exchanged for a token containing all scopes the user has granted the project.
For example, suppose an app helps users identify interesting local events.
The app lets users view videos about the events, rate the videos, and add the
videos to playlists. Users can also use the app to add events to their Google
Calendars.
In this case, at sign-in time, the app might not need or request access to
any scopes. However, if the user tried to rate a video, add a video to a
playlist, or perform another YouTube action, the app could request access to
the https://www.googleapis.com/auth/youtube.force-ssl
scope.
Similarly, the app could request access to the
https://www.googleapis.com/auth/calendar
scope if the user tried
to add a calendar event.
To implement incremental authorization, you complete the normal flow for requesting an access
token but make sure that the authorization request includes previously granted scopes. This
approach allows your app to avoid having to manage multiple access tokens.
The following rules apply to an access token obtained from an incremental authorization:
scope
values included in the response.The language-specific code samples in Step 1: Set authorization
parameters and the sample HTTP/REST redirect URL in Step 2:
Redirect to Google's OAuth 2.0 server all use incremental authorization. The code samples
below also show the code that you need to add to use incremental authorization.
$client->setIncludeGrantedScopes(true);
Python In Python, set the include_granted_scopes
keyword argument to true
to
ensure that an authorization request includes previously granted scopes. It is very possible that
include_granted_scopes
will not be the only keyword argument that you set, as
shown in the example below.
authorization_url, state = flow.authorization_url(Ruby
# 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')
auth_client.update!(Node.js
:additional_parameters => {"include_granted_scopes" => "true"}
)
const authorizationUrl = oauth2Client.generateAuthUrl({HTTP/REST
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
/** Pass in the scopes array defined above.
* Alternatively, if only one scope is needed, you can pass a scope URL as a string */
scope: scopes,
// Enable incremental authorization. Recommended as a best practice.
include_granted_scopes: true
});
In this example, the calling application requests access to retrieve the
user's YouTube Analytics data in addition to any other access that the user
has already granted to the application.
GET https://accounts.google.com/o/oauth2/v2/auth?
scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fyt-analytics.readonly&
access_type=offline&
state=security_token%3D138rk%3Btarget_url%3Dhttp...index&
redirect_uri=http%3A%2F%2Flocalhost%2Foauth2callback&
response_type=code&
client_id=client_id&
include_granted_scopes=true
Access tokens periodically expire and become invalid credentials for a related API request. You
can refresh an access token without prompting the user for permission (including when the user is
not present) if you requested offline access to the scopes associated with the token.
access_type
HTTPoffline
when redirecting the user toRequesting offline access is a requirement for any application that needs to access a Google
API when the user is not present. For example, an app that performs backup services or
executes actions at predetermined times needs to be able to refresh its access token when the
user is not present. The default style of access is called online
.
Server-side web applications, installed applications, and devices all obtain refresh tokens
during the authorization process. Refresh tokens are not typically used in client-side
(JavaScript) web applications.
If your application needs offline access to a Google API, set the API client's access type to
offline
:
$client->setAccessType("offline");
After a user grants offline access to the requested scopes, you can continue to use the API
client to access Google APIs on the user's behalf when the user is offline. The client object
will refresh the access token as needed.
In Python, set the access_type
keyword argument to offline
to ensure
that you will be able to refresh the access token without having to re-prompt the user for
permission. It is very possible that access_type
will not be the only keyword
argument that you set, as shown in the example below.
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')
After a user grants offline access to the requested scopes, you can continue to use the API
client to access Google APIs on the user's behalf when the user is offline. The client object
will refresh the access token as needed.
If your application needs offline access to a Google API, set the API client's access type to
offline
:
auth_client.update!(
:additional_parameters => {"access_type" => "offline"}
)
After a user grants offline access to the requested scopes, you can continue to use the API
client to access Google APIs on the user's behalf when the user is offline. The client object
will refresh the access token as needed.
If your application needs offline access to a Google API, set the API client's access type to
offline
:
const authorizationUrl = oauth2Client.generateAuthUrl({
// 'online' (default) or 'offline' (gets refresh_token)
access_type: 'offline',
/** Pass in the scopes array defined above.
* Alternatively, if only one scope is needed, you can pass a scope URL as a string */
scope: scopes,
// Enable incremental authorization. Recommended as a best practice.
include_granted_scopes: true
});
After a user grants offline access to the requested scopes, you can continue to use the API
client to access Google APIs on the user's behalf when the user is offline. The client object
will refresh the access token as needed.
Access tokens expire. This library will automatically use a refresh token to obtain a new access
token if it is about to expire. An easy way to make sure you always store the most recent tokens
is to use the tokens event:
oauth2Client.on('tokens', (tokens) => {
if (tokens.refresh_token) {
// store the refresh_token in your secure persistent database
console.log(tokens.refresh_token);
}
console.log(tokens.access_token);
});
This tokens event only occurs in the first authorization, and you need to have set your
access_type
to offline
when calling the generateAuthUrl
method to receive the refresh token. If you have already given your app the requisiste permissions
without setting the appropriate constraints for receiving a refresh token, you will need to
re-authorize the application to receive a fresh refresh token.
To set the refresh_token
at a later time, you can use the setCredentials
method:
oauth2Client.setCredentials({
refresh_token: `STORED_REFRESH_TOKEN`
});
Once the client has a refresh token, access tokens will be acquired and refreshed automatically
in the next call to the API.
To refresh an access token, your application sends an HTTPS POST
request to Google's authorization server (https://oauth2.googleapis.com/token
) that
includes the following parameters:
Fields
client_id
The client ID obtained from the API Console.
client_secret
The client secret obtained from the API Console.
grant_type
As
defined in the
OAuth 2.0 specification,
this field's value must be set to refresh_token
.
refresh_token
The refresh token returned from the authorization code exchange.
The following snippet shows a sample request:
POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencodedclient_id=your_client_id&
client_secret=your_client_secret&
refresh_token=refresh_token&
grant_type=refresh_token
As long as the user has not revoked the access granted to the application, the token server
returns a JSON object that contains a new access token. The following snippet shows a sample
response:
{
"access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
"expires_in": 3920,
"scope": "https://www.googleapis.com/auth/drive.metadata.readonly",
"token_type": "Bearer"
}
Note that there are limits on the number of refresh tokens that will be issued; one limit per
client/user combination, and another per user across all clients. You should save refresh tokens
in long-term storage and continue to use them as long as they remain valid. If your application
requests too many refresh tokens, it may run into these limits, in which case older refresh tokens
will stop working.
In some cases a user may wish to revoke access given to an application. A user can revoke access
by visiting
Account Settings. See the
Remove
site or app access section of the Third-party sites & apps with access to your account
support document for more information.
It is also possible for an application to programmatically revoke the access given to it.
Programmatic revocation is important in instances where a user unsubscribes, removes an
application, or the API resources required by an app have significantly changed. In other words,
part of the removal process can include an API request to ensure the permissions previously
granted to the application are removed.
To programmatically revoke a token, call revokeToken()
:
$client->revokeToken();
Python To programmatically revoke a token, make a request to
https://oauth2.googleapis.com/revoke
that includes the token as a parameter and sets the
Content-Type
header:
requests.post('https://oauth2.googleapis.com/revoke',Ruby
params={'token': credentials.token},
headers = {'content-type': 'application/x-www-form-urlencoded'})
To programmatically revoke a token, make an HTTP request to the oauth2.revoke
endpoint:
uri = URI('https://oauth2.googleapis.com/revoke')
response = Net::HTTP.post_form(uri, 'token' => auth_client.access_token)
The token can be an access token or a refresh token. If the token is an access token and it has
a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is
200
. For error conditions, a status code 400
is returned along with an
error code.
To programmatically revoke a token, make an HTTPS POST request to /revoke
endpoint:
const https = require('https');// Build the string for the POST request
let postData = "token=" + userCredential.access_token;// Options for POST request to Google's OAuth 2.0 server to revoke a token
let postOptions = {
host: 'oauth2.googleapis.com',
port: '443',
path: '/revoke',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};// Set up the request
const postReq = https.request(postOptions, function (res) {
res.setEncoding('utf8');
res.on('data', d => {
console.log('Response: ' + d);
});
});postReq.on('error', error => {
console.log(error)
});// Post the request with data
postReq.write(postData);
postReq.end();
The token parameter can be an access token or a refresh token. If the token is an access token and it has
a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is
200
. For error conditions, a status code 400
is returned along with an
error code.
To programmatically revoke a token, your application makes a request to
https://oauth2.googleapis.com/revoke
and includes the token as a parameter:
curl -d -X -POST --header "Content-type:application/x-www-form-urlencoded" \
https://oauth2.googleapis.com/revoke?token={token}
The token can be an access token or a refresh token. If the token is an access token and it has a
corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the HTTP status code of the response is
200
. For error conditions, an HTTP status code 400
is returned along
with an error code.
An additional step you should take to protect your users' accounts is implementing Cross-Account
Protection by utilizing Google's Cross-Account Protection Service. This service lets you
subscribe to security event notifications which provide information to your application about
major changes to the user account. You can then use the information to take action depending on
how you decide to respond to events.
Some examples of the event types sent to your app by Google's Cross-Account Protection Service are:
https://schemas.openid.net/secevent/risc/event-type/sessions-revoked
https://schemas.openid.net/secevent/oauth/event-type/token-revoked
https://schemas.openid.net/secevent/risc/event-type/account-disabled
See the
Protect user accounts with Cross-Account Protection page
for more information on how to implement Cross Account Protection and for the full list of available events.
#1. Django - render, redirect (補充) - iT 邦幫忙::一起幫忙解決難題
from django.shortcuts import render import datetime def ... app return redirect('another_view') #redirect裡面的參數放view的名稱 def ...
#2. How can I redirect from view In Django - Stack Overflow
As already suggested by @mdegis you can use the Django redirect function to redirect to another view or url. ... You can pass positional or ...
#3. The Ultimate Guide to Django Redirects - Real Python
Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. A view returning a redirect has ...
A view name, possibly with arguments: reverse() will be used to reverse-resolve the ... which will be used as-is for the redirect location.
#5. Django - Page Redirection - Tutorialspoint
The 'redirect' method takes as argument: The URL you want to be redirected to as string A view's name. The myapp/views looks like the following so far − def ...
#6. Django URL重定向的3种方法详解 - 知乎专栏
后台工作还是由reverse方法来完成的。 def my_view(request): ... return redirect('some-view-name', foo='bar').
#7. Django Redirects | Complete Guide of Redirects - javatpoint
What are Redirects? · # views.py · from django.shortcuts import redirect · def redirect_view(request): · response = redirect('/redirect-success/') ...
#8. The Essential Guide of URL Redirects in Django - DataFlair
Django Redirects – The Essential Guide of URL Redirects in Django ... Websites, in general, have URL redirection to enhance the user experience and it's necessary ...
#9. django.shortcuts redirect Example Code - Full Stack Python
base import TemplateResponseMixin, TemplateView, View from django.views.generic.edit import FormView from ..exceptions import ImmediateHttpResponse from ...
#10. The Complete Guide to Django Redirects | Nick McCullum
Django provides a special RedirectView class when the only requirement of a view function is to redirect the user. This class provides the ...
#11. How to Add a Redirect to Your Django Page? - AskPython
The Django redirect() Function. A webpage can be redirected using the redirect() function in 3 ways: Using Views as it's arguments; Using URLs directly as ...
#12. How can I redirect from view In Django - Pretag
You can pass positional or keyword argument(s) to the redirect shortcut using the reverse() method and the named url of the view you're ...
#13. [Solved] Http django redirect to view
I have one view that I want to do some stuff in and then redirect to another view with a success message. The signature of the method that I want to ...
#14. Introduction to HTTP Redirects in Django - YouTube
#15. redirect url django Code Example
from django.shortcuts import redirect def my_view(request): # ... return redirect('some-view-name', foo='bar')
#16. How to Redirect to Another Page in Django - Learning about ...
So, in this views.py file, we create a function that redirects the user to whatever page we want. This page can be on our website or a completely separate ...
#17. Django redirect 重定向. 跨站重定向(一個網址)
由name='book_price'連結到def views.show_book_price 將return redirect('book_price', price=price)的price傳遞到def show_book_price(request, price):.
#18. Redirect to another URL in Django Template View - gists ...
Redirect to another URL in Django Template View. GitHub Gist: instantly share code, notes, and snippets.
#19. 【Django】响应数据、重定向(redirect)、反向解析(reverse)
from django.shortcuts import render, redirect from django.views import View from django import http class HttpResponseView(View): def ...
#20. django redirect to another view with context | Newbedev
django redirect to another view with context. I would use session variables in order to pass some context through a redirect. It is about the only way to do ...
#21. Redirecting URLs in Django - Django 1.10 Tutorial - OverIQ.com
The redirect() is shortcut function to redirect the users to different URLs. It accepts URL path or name of the URL pattern to redirect to. To use it first ...
#22. Django Tips #1 redirect - Simple is Better Than Complex
A reverse url name (accept view arguments);. from django.shortcuts import redirect from simple_blog.models import Post def post_view(request ...
#23. Django Open Redirect Guide: Examples and Prevention
In this post, we'll cover Django Open Redirects including a thorough overview, ... The redirect function takes more than just views; ...
#24. How to redirect to named url pattern directly from urls py in ...
from django.views.generic import RedirectView urlpatterns = patterns('', url(r'^some-page/$', RedirectView.as_view(url='/')), .
#25. The “next” parameter, redirect, django.contrib.auth.login - py4u
I'm trying to redirect users to custom url "/gallery/(username)/" after ... Django's login view django.contrib.auth.views.login accepts a dictionary named ...
#26. Implementing POST Redirect in Django - Coursera
You will learn how to use the Django console and scripts to work with your application objects interactively. View Syllabus ...
#27. Python Examples of django.shortcuts.redirect - ProgramCreek ...
This page shows Python examples of django.shortcuts.redirect. ... Project: django-classified Author: slyapustin File: views.py License: MIT License, 6 votes ...
#28. Python generic.RedirectView類代碼示例- 純淨天空
RedirectView類代碼示例,django.views.generic. ... Gets the redirect patterns out of the database and assigns them to the django patterns object.
#29. RedirectView - django - Python documentation - Kite
RedirectView - 5 members - Redirects to a given URL. ... from django.conf.urls import url from django.views.generic.base import RedirectView from ...
#30. Django页面重定向 - 易百教程
在“redirect”方法需要作为参数:URL要被重定向到的字符串的视图名字。 myapp/views 到现在为止如下所示 − def hello(request): today = datetime.datetime.now().date() ...
#31. Django redirect to another view
How does one redirect from one View to another (next-going one): redirect django parameters. Django makes it possible to separate python and HTML, ...
#32. 十六)Django - redirect的錯誤示範
Reverse for 'result' not found. 'result' is not a valid view function or pattern name. Django說他找不到view result!?但說明提到 ...
#33. How to Redirect Stdout to Streaming Response in Django
console_streaming/urls.py from django.urls import path from web import views urlpatterns = [ path('stream/', views.stream), ] ...
#34. 5.10 Redirecting the Homepage - InformIT
Example 5.77: Project Code. suorganizer/views.py in 5fb0dff63a 1 from django.shortcuts import redirect 2 3 4 def redirect_root(request): 5 ...
#35. django views如何重定向到带参数的url - 开发技术- 亿速云
redirect 类似HttpResponseRedirect的用法,也可以使用字符串的url格式/..index/?a=add reverse 可以直接用views函数来指定重定向的处理函数,args是url ...
#36. python - 带有附加参数的Django redirect() - IT工具网
原文 标签 python django django-views ... def first(request): return redirect('confirm') def confirm(request): return render(request, 'template.html')
#37. URL重定向的HttpResponseDirect,redirect和reverse的用法详解
Django 基础:URL重定向的HttpResponseDirect,redirect和reverse的用法 ... 在视图views.py中利用HttpResponseDirect重新定向至包含参数的URL对于包含 ...
#38. Django | Redirect View after “liking” without scrolling - Reddit
Django | Redirect View after “liking” without scrolling. I'm making a simple blog app. I have added the ability to "like" a post on your feed.
#39. How to Make Django Redirect WWW to Your Bare Domain
Otherwise, we return the result of the get_response function, allowing the remaining middleware and view to run as normal. To deploy this, we ...
#40. How to customize django change form redirect url | - abidibo.net
you'll pass the next parameter as a query string parameter; the add/change/delete views should read this parameter and set it in the view ...
#41. RedirectView -- Classy CBV
RedirectView in Django 3.0. Provide a redirect on any GET request. ... class RedirectView. from django.views.generic import RedirectView.
#42. Django 知识库:redirect()重定向- 杜赛的博客
return redirect('another_url', id=id). 依然可以用关键字参数传递变量到被跳转的视图中。 在 reverse() 的章节中我们是这样写的: return ...
#43. Django项目实战- redirect 页面跳转 - 博客园
render是渲染变量到模板中,而redirect是HTTP中的1个跳转的函数,一般会生成302 ... HttpResponse from django.views.generic.base import View from ...
#44. Custom redirects in the django admin - szotten.com
Now, ideally i'd like the user to be redirected back to the main site on save, instead of to the default django admin list view.
#45. 十三Django-重定向机制- 简书
当您成功登录时,Django会将您重定向到您最初请求的URL ... 注意不要在一级路由中使用命名空间views.py def redi2(request): return redirect(reverse('user:login'))
#46. Introduction to Django Views | Pluralsight
The response can be a simple HTTP response, an HTML template response, or an HTTP redirect response that redirects a user to another page. Views ...
#47. Django basis of redirect () - Programmer Sought
Parameters can be: A model: the model will be called get_absolute_url () function; A view, may be provided with the function: may be used to reverse resolve ...
#48. URL重定向的HttpResponseDirect, redirect和reverse的用法詳解
利用django開發web應用, 我們經常需要進行URL重定向,有時候還需要給URL傳遞額外的參數。 ... return redirect('some-view-name', foo='bar').
#49. View Redirect Decorators - djangosnippets
Temporary and permanent view redirect decorators. ... from functools import wraps from django.http import HttpResponsePermanentRedirect, ...
#50. Djangoのredirect()の使い方【Python】 - なるぽのブログ
これは文字列のビュー名、またはパス、またはURL、またはモデルのオブジェクトです。 redirect('my-view-name') # ビュー名 redirect ...
#51. Django: cannot redirect to UpdateView after item is deleted
Im creating a view just for deleting ListItems that correspond to a List objects through a ForeignKeyI can successfully delete the ListI...
#52. Django View中跳转的陷阱 - 华为云社区
Django 中在view中对接口做重定向常用的有两种方式。 - shortcuts.redirect 可以传入url或者view name,view name可...
#53. Django URL重定向的HttpResponseDirect, redirect和reverse方法
HttpResponseDirect方法HttpResponseRedirect是django首選的URL重定向方法, ... 除此之外,redirect還可以根據對象Object重定向和根據視圖view重 ...
#54. Django's login_required decorator does not redirect to ...
I have added the login_required decorator to one of my views. If I enter the URL in the browser which executes this view, the browser correctly redirects to ...
#55. Redirects — Wagtail Documentation 2.15.1 documentation
redirects to INSTALLED_APPS and wagtail.contrib.redirects.middleware.RedirectMiddleware to MIDDLEWARE in your project's Django settings file. INSTALLED_APPS ...
#56. Django simple url redirect - Django Snipplr Social Repository
from django.http import HttpResponseRedirect. def myview(request): Â ... Â return HttpResponseRedirect("/path/").
#57. Djangoでリダイレクトをする方法についてまとめました ...
View の定義. from django.shortcuts import redirect from django.http import HttpResponse. def redirect_view(request):
#58. Django retourne redirect () avec des paramètres - it-swarm-fr ...
Dans ma fonction de vue, je souhaite appeler une autre vue et lui transmettre des données:return redirect('some-view-name', backend, form.cleaned_data) ...
#59. How to Serve Protected Content With Django (Without ...
Using Nginx's X-Accel-Redirect you can apply permissions to files served directly ... Now the goal is to write a view that will only serve this document to ...
#60. Django redirect - Code Helper
from django.shortcuts import redirect def my_view(request): # ... return redirect('some-view-name', foo='bar')
#61. Passing arguments on redirect (Django 1.1) - Google Groups
to Django users. I'm using the redirect() function provided in Django 1.1: ... And I'd like to redirect to that view from another view such that I
#62. [Django]Viewのリダイレクト時にパラメータを追加する
View で普通にリダイレクトしたい場合、 redirect() 関数を使用して以下のように実装すればリダイレクトさせることができます。 return redirect(' ...
#63. Django: Redirect already logged user by class based view
I want to redirect to the main page if the user is already authenticated. So I want a redirect from / to /main. views.py :.
#64. [Django] render 와 redirect 의 차이 - 수학과의 좌충우돌 ...
이 때 context 로 원하는 인자를, 즉 view 에서 사용하던 파이썬 변수를 html 템플릿으로 ... views.py from django.shortcuts import redirect def ...
#65. Django: How can I take the choice in drop-down list and ...
So I decided to redirect using redirect from django.shortcuts. I changed my teacher_interface view, so that it took the id of the chosen by ...
#66. redirectの使い方【パラメータの使い方の具体例もあります】
django でリダイレクトの設定をするには、redirectメソッドを使うと便利です。 ... 次はviewの名前です。viewの名前とは、urlpatternsで設定したname='somename'という ...
#67. Django - Redirect(리다이렉트) 하기 - 배움이 즐거운 개발자
Redirect. HttpResponseRedirect이용. 1. views.py 를 수정한다. 1) from django.http import HttpResponseRedirect 추가. 2) django.urls import ...
#68. Django Tutorial Part 10: Testing a Django web application
This tutorial shows how to write automated tests for Django, by adding a ... and also Django-specific assertions to test if a view redirects ...
#69. Returning URLs - Django REST framework
Django, API, REST, Returning URLs. ... from rest_framework.reverse import reverse from rest_framework.views import APIView from django.utils.timezone import ...
#70. Django Url naming and namespaces - Web Forefront
A project's internal links or url references (e.g. <a href='/'>Home Page</a> ) tend to be hard-coded, whether it's in view methods to redirect users to certain ...
#71. How to manage a redirect request after a jQuery Ajax call
If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function. For ...
#72. url - Django Template Tag - GeeksforGeeks
Django templates not only allow passing data from view to template, ... Click on the link and it will redirect to other url.
#73. (Django) render 와 redirect의 차이 - velog
현재 인턴중인 회사에서 기존에 쓰인 소스코드의 url, view, template을 모두를 수정해야 하는 일이 생겼다. 이들의 관계성에 대한 이해가 부족해서 알고 ...
#74. [Django] 장고. http redirect하기 - 개발자의 취미생활 - 티스토리
[Django] 장고. http redirect하기 ... from django.conf.urls import url ... url(r'^areas/(?P<area>[가-힣]+)/results$', views.results),.
#75. django shortcuts render - Secretaria de Salud Morelos
Django's Views. The redirect() function is used to redirect to the specific URL. from django.shortcuts import render def joke_view (request): # create ...
#76. Django中几种重定向方法- python - 脚本之家
这篇文章主要介绍了Django中几种重定向方法, ... return redirect(reverse('commons.views.invoice_return_index', args=[])) #跳转到index界面.
#77. A Guide to Build a URL Shortener App with Django - Geekflare
Later you'll see how to implement the error display in the template. Redirect view. The redirect_url_view , is a little bit simpler.
#78. 【Django】パラメータを渡してリダイレクトさせる(redirect ...
redirect 関数を利用するときにパラメータを付与するには以下のような実装になります。 views.py from django.urls import reverse from urllib.parse ...
#79. Question Django testing: RequestFactory() follow redirect
In Django, I have a view, which will redirect to the register page for certain ... from .views import my_view from django.test import RequestFactory() def ...
#80. How To Redirect To Url In Python Flask - Vegibit
The use of redirect is highlighted in the code here. flask-tutorial\app.py. from flask import Flask, render_template, request, redirect app ...
#81. Django 路由 - 菜鸟教程
在views.py 中,从django.urls 中引入reverse,利用reverse("路由别名") 反向解析: return redirect(reverse("login")). 在模板templates 中的HTML 文件中,利用{% url ...
#82. Use standard redirects - don't break the back button! - W3C
Techniques to use and techniques to avoid. Don't use "refresh" to redirect. If you want http://www.example.org/foo to actually display ...
#83. В django, return redirect не дает мне требуемого вывода
views.py def auth_check_manager(request): if not request.user.is_authenticated: return redirect('/'). ниже приведен снимок url.py
#84. Django redirect to another url. Subscribe to RSS
When you try to access a page of Django admin without ... We will make a new function which will redirect the view to a different URL, ...
#85. Django Login and Logout Tutorial | LearnDjango.com
Our login functionality now works but to make it better we should specify where to redirect the user upon a successful login. In other words, ...
#86. Using OAuth 2.0 for Web Server Applications | YouTube Data ...
The redirect URIs are the endpoints to which the OAuth 2.0 server can send ... https://www.googleapis.com/auth/youtube.readonly, View your ...
#87. Django Login Logout Authentication System Using Admin ...
This simple example, has the ability to validate username and password and authenticate user. Customize the Django Login View. We can pass some ...
#88. Debugging in Visual Studio Code
The Run view displays all information related to running and debugging and has a ... in a terminal or command prompt and redirect input/output as needed.
#89. Django /從redirect_to到RedirectView - 優文庫 - UWENKU
既然你知道,我們不能使用從Django 1.5中的django.views.generic.simple ... 您可以使用 redirect instead ... 來源:"No module named simple」 error in Django.
#90. Django3.0 solves the problem of error reporting in reverse ...
One 、 Problems arise Reference resources Django The teachi. ... In the application view file “ Applied namespace: Redirect url Of name” ...
#91. The redirects app — Документация Django 1.5.2 - Djbook.ru
The RedirectFallbackMiddleware does all of the work. Each time any Django application raises a 404 error, this middleware checks the redirects database for ...
#92. How To Secure Nginx with Let's Encrypt on Ubuntu 20.04
If that's successful, certbot will ask how you'd like to configure your HTTPS settings. Output. Please choose whether or not to redirect HTTP traffic to HTTPS, ...
#93. redirect in django views
The final step in the form-handling part of the view is to redirect to another ... views.py from django.shortcuts import render, redirect from.forms import ...
#94. HTTP request headers · Cloudflare Fundamentals docs
HTTP request headers. Cloudflare passes all HTTP request headers to your origin web server and adds additional headers as specified below. CF-Connecting-IP.
#95. Django学习笔记(2)——Django 基础 - ICode9
接下来编写登录页面业务逻辑代码,打开/myproject/myapp/views.py,增加以下代码。 from django.shortcuts import render,HttpResponse,redirect ...
#96. Laravel 302 redirect, unable to login - laravelquestions.com
I have laravel app, when testing it on opera browser and chrome, the login (form validation) works accordingly. The issue is when I test it ...
#97. How To Create a Search Menu - W3Schools
margin: 0; } /* Style the navigation links */ #myMenu li a { padding: 12px; text-decoration: none; color: black; display: block } #myMenu li a:hover {
#98. Django Unleashed - Google 圖書結果
Short of creating a separate homepage view, directing our homepage to an existing ... In this instance, http://site.django unleashed.com/ will redirect to ...
#99. Designing Microservices with Django: An Overview of Tools ...
Class based view for signing up # user/views.py from django.contrib.auth import ... django.shortcuts import render, redirect from django.views import View ...
django view redirect 在 Introduction to HTTP Redirects in Django - YouTube 的美食出口停車場
... <看更多>