instagram css_使用Facebook,Instagram和LinkedIn进行Django身份验证

instagram css

介绍 ( Introduction )

For users of internet services, there are only a few things worse than having to manually sign in (and sign-up) with different websites. The ordeal of the manual sign-in process can be associated with the difficulty that the user may experience in having to remember multiple strong passwords.

对于互联网服务的用户而言,与必须手动使用不同的网站登录(和注册)相比,只有几件事。 手动登录过程的艰辛可能与用户在记住多个强密码时可能遇到的困难有关。

The inability to remember a password could lead to the creation of multiple accounts on the same platform or the outright switch to browsing as an unauthenticated user (where it doesn’t prevent access to the sought-after information or service).

无法记住密码可能会导致在同一平台上创建多个帐户,或者直接切换为以未经身份验证的用户身份浏览(这不会阻止访问所寻求的信息或服务)。

Modern web applications solve this problem using social authentication, which is primarily a way to allow users to sign in (and sign-up) with the application using login information from a social network provider that they already have an account with.

现代Web应用程序使用社交身份验证解决了这个问题,这主要是允许用户使用来自已经拥有帐户的社交网络提供商的登录信息来登录(和注册)该应用程序的方法。

In this tutorial, we will build a simple Django application that allows users to sign in via their Facebook, Instagram and LinkedIn accounts. To achieve this, we will use the social-auth-app-django library. We will also learn how to extract additional information such as profile picture and username from the respective social accounts.

在本教程中,我们将构建一个简单的Django应用程序,该应用程序允许用户通过其Facebook,Instagram和LinkedIn帐户登录。 为此,我们将使用social-auth-app-django库。 我们还将学习如何从相应的社交帐户中提取其他信息,例如个人资料图片和用户名。

At the end of this tutorial, we will have the final application that works like this:

在本教程的最后,我们将有一个最终的应用程序,其工作方式如下:

The source code for this project is available here on GitHub.

该项目的源代码可以在这里 GitHub上。

先决条件 ( Prerequisites )

You need the following items installed on your machine to follow along with this tutorial:

您需要在计算机上安装以下项目才能跟随本教程:

  1. Python3

    Python3
  2. Pipenv

    Pipenv

Pipenv is a production-ready tool that aims to bring the best of all packaging worlds to the Python world. It harnesses Pipfile, pip, and virtualenv into one single command.

Pipenv是可用于生产的工具,旨在将所有包装领域的精华带入Python世界。 它将Pipfile,pip和virtualenv整合到一个命令中。

This tutorial assumes that the reader has basic working knowledge with Django. You also need to have an account with Facebook, Instagram and LinkedIn.

本教程假定读者具有Django的基本工作知识。 您还需要在Facebook,Instagram和LinkedIn上拥有一个帐户。

Let’s dive right in!

让我们潜入吧!

设置Django应用 ( Setting up the Django app )

In this section, we will up a new Django project and install dependencies. Let’s start by creating a new folder and making it the present working directory:

在本节中,我们将建立一个新的Django项目并安装依赖项。 让我们从创建一个新文件夹开始,并使其成为当前的工作目录:

$mkdir django_social_app
    $ cd django_social_app

We will create and activate a new virtual environment using Pipenv; this has the effect of creating an isolated Python environment and preventing us from polluting the global package directory when we install Django dependencies. We will also install django and social-auth-app-django:

我们将使用Pipenv创建并激活一个新的虚拟环境; 这具有创建隔离的Python环境并防止我们在安装Django依赖项时污染全局包目录的作用。 我们还将安装djangosocial-auth-app-django

$ pipenv shell
    $ pipenvinstall django social-auth-app-django

social-auth-app-django simplifies the implementation of social authentication with Django.

social-auth-app-django简化了使用Django进行社交身份验证的过程。

Let’s create (and navigate into) a new Django project, we will call it social_app:

让我们创建(并导航到)一个新的Django项目,我们将其social_app:

$(django_social_app) $ django-admin startproject social_app
    $ (django_social_app) $ cd social_app

Note: It is important that we run the commands from the terminal that is sourced into the virtual environment i.e displays (django_social_app) at the beginning of each command line.

注意:重要的是,我们从源于虚拟环境的终端运行命令,即在每个命令行的开头显示(django_social_app)。

Next, we will create a Django application called core, this application will contain all our views and templates:

接下来,我们将创建一个名为core的Django应用程序,该应用程序将包含我们的所有视图和模板:

(django_social_app) $ python manage.py startapp core

Note: You need to be in the parent social_app directory to run ‘python manage.py *’ commands.

注意:您需要在父social_app目录中运行“ python manage.py *”命令。

Let’s find the settings.py file in the social_app project and add both core and social-auth-app-django as INSTALLED_APPS:

让我们在social_app项目中找到settings.py文件,并将coresocial-auth-app-djangoINSTALLED_APPS

#social_app/settings.py

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'social_django', # add this 
        'core' # add this
      ]

Finally, let’s migrate the database:

最后,让我们迁移数据库:

(django_social_app) $ python manage.py migrate

配置身份验证类 (Configuring the authentication classes)

Behind the scenes, Django maintains a list of “authentication backends” that it checks during user authentication. If the first authentication method fails, Django tries the second one, and so on, until all backends have been attempted.

在幕后,Django维护了一个在用户身份验证期间检查的“身份验证后端”列表。 如果第一种身份验证方法失败,则Django尝试第二种身份验证,依此类推,直到尝试了所有后端。

The AUTHENTICATION_BACKENDS array contains a list of authentication backend classes (as strings) and is by default set to:

AUTHENTICATION_BACKENDS数组包含身份验证后端类(作为字符串)的列表,默认情况下设置为:

['django.contrib.auth.backends.ModelBackend']

We can update it and add new authentication classes in order to allow authentication with the social platforms we are considering in this tutorial.

我们可以对其进行更新并添加新的身份验证类,以允许使用我们在本教程中考虑的社交平台进行身份验证。

To update it this, simply add the following code in the settings.py file:

要对此进行更新,只需在settings.py文件中添加以下代码:

#social_app/settings.py

    #add this
    AUTHENTICATION_BACKENDS = [
        'social_core.backends.linkedin.LinkedinOAuth2',
        'social_core.backends.instagram.InstagramOAuth2',
        'social_core.backends.facebook.FacebookOAuth2',
        'django.contrib.auth.backends.ModelBackend',
    ]

We just added the authentication backend classes for Linkedin, Instagram and Facebook.

我们刚刚为Linkedin,Instagram和Facebook添加了身份验证后端类。

You can find a list of the authentication backends classes supported by social-auth-app-django here.

您可以在此处找到social-auth-app-django支持的身份验证后端类的列表

添加模板和静态文件 (Adding templates and static files)

We’ve only worked on setting up and configuring the application, let’s move on to something visual now. In this section, we will build the foundation of the templates that will display the application.

我们仅致力于设置和配置应用程序,现在让我们继续进行可视化操作。 在本节中,我们将建立显示应用程序的模板的基础。

Let’s create a new folder in the coredirectory, we will call this folder templates:

让我们在core目录中创建一个新文件夹,我们将其称为文件夹templates

(django_social_app) $ cd core/
    (django_social_app) $ mkdir templates/

Create three files within the templates directory and call them:

templates目录中创建三个文件,然后调用它们:

  1. base.html

    base.html
  2. login.html

    login.html
  3. home.html

    home.html

Now, open the base.html file and paste in the following snippet:

现在,打开base.html文件并粘贴以下代码段:

<!-- templates/base.html -->

    {% load static %}
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO"
            crossorigin="anonymous" />
        <link rel="stylesheet" href="{% static 'css/index.css' %}" />
        <title>Social Auth with Django</title>
    </head>
    <body>
        <div class="container-fluid">
            <div>
                <h1 class="text-white text-center">{% block title %}{% endblock %}</h1>
                <div class="card p-5">
                    {% block content %}
                    {% endblock %}
                </div>
            </div>
        </div>
    </body>
    </html>

Paste in the following snippet in the login.html file:

将以下代码段粘贴到login.html文件中:

<!-- templates/login.html -->

    {% extends 'base.html' %}
    {% block title %} Sign in {% endblock %}
    {% block content %}
    <div class="row">
        <div class="col-md-8 mx-auto social-container my-2 order-md-1">
            <button class="btn btn-danger  mb-2">
                <a href="#">Login with Instagram</a>
            </button>
            <button class="btn btn-primary mb-2">
                <a href="#">Login with Facebook
                </a>
            </button>
            <button class="btn btn-info mb-2">
                <a href="#">Login with LinkedIn</a>
            </button>
        </div>
    </div>
    </div>
    {% endblock %}

Lastly, update the home.html file with the code below:

最后,使用以下代码更新home.html文件:

<!-- templates/home.html -->

    {% extends 'base.html' %}
    {% block title %} Home {% endblock %}
    {% block content %}
    <div class="row">
        <div class="col-sm-12 mb-3">
            <h4 class="text-center"> Welcome {{ user.username }} </h4>
        </div>
    </div>
    {% endblock %}

We need some styles to help our code look nice when rendered, so let’s create a folder called static in the root of the core folder and we will store our styles there.

我们需要一些样式来帮助我们的代码在渲染时看起来不错,所以让我们在core文件夹的根目录中创建一个名为static的文件夹,并将样式存储在此文件夹中。

Create a folder called css folder within the static directory and finally, create an index.css file within the css folder.

static目录中创建一个名为css文件夹的文件夹,最后,在css文件夹中创建一个index.css文件。

Now open the index.css file and update it with the following code:

现在打开index.css文件,并使用以下代码对其进行更新:

/_ index.css _/

    img {
      border: 3px solid #282c34;
    }
    .container-fluid {
      height: 100vh;
      background-color: #282c34;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .container-fluid > div {
      width: 85%;
      min-width: 300px;
      max-width: 500px;
    }
    .card {
      width: 100%;
    }
    .social-container {
      display: flex;
      flex-direction: column;
      justify-content: center;
    }
    .btn a, .btn a:hover {
      color: white;
      text-decoration: none ;
    }

设置视图和URL (Setting up the Views and URLs)

In this section, we will define the Views and register the URLs that the application needs to work, so open the core/views.py file and replace its content with the snippet below:

在本节中,我们将定义视图并注册应用程序需要工作的URL,因此打开core/views.py文件,并将其内容替换为下面的代码段:

# core/views.py

    from django.shortcuts import render
    from django.contrib.auth.decorators import login_required

    # Create your views here.
    def login(request):
      return render(request, 'login.html')

    @login_required
    def home(request):
      return render(request, 'home.html')

Next, we will register the routes for the application and attach their matching view functions. Replace the content of the social_app/urls.py file with the code below:

接下来,我们将为应用程序注册路由并附加其匹配的视图功能。 用以下代码替换social_app/urls.py文件的内容:

# social_app/urls.py

    from django.contrib import admin
    from django.urls import path, include
    from django.contrib.auth import views as auth_views
    from core import views

    urlpatterns = [
        path('admin/', admin.site.urls),         path("login/", views.login, name="login"),
        path("logout/", auth_views.LogoutView.as_view(), name="logout"),
        path('social-auth/', include('social_django.urls', namespace="social")),
        path("", views.home, name="home"),
    ]

In the settings.py file, we need to set four new values — LOGIN_URL, LOGOUT_URL, LOGIN_REDIRECT_URL and LOGOUT_REDIRECT_URL — because they will be used in redirecting the user when authentication is complete:

settings.py文件中,我们需要设置四个新值LOGIN_URLLOGOUT_URLLOGIN_REDIRECT_URLLOGOUT_REDIRECT_URL ,因为它们将在身份验证完成后用于重定向用户:

# social_app/settings.py

    # [...]

    LOGIN_URL = 'login'
    LOGIN_REDIRECT_URL = 'home'
    LOGOUT_URL = 'logout'
    LOGOUT_REDIRECT_URL = 'login'

    # [...]

Fantastic! We can now run the application to see what we’ve built so far. Let’s start the server with this command:

太棒了! 现在,我们可以运行该应用程序以查看到目前为止已构建的内容。 让我们使用以下命令启动服务器:

(django_social_app) $ python manage.py runserver

Note: You need to be in the parent social_app directory to run ‘python manage.py *’ commands.

注意:您需要在父social_app目录中运行“ python manage.py *”命令。

We can view the application on http://localhost:8000, though we will be redirected to /login since we aren't authenticated:

我们可以在http:// localhost:8000上查看该应用程序,但是由于未通过身份验证,我们将重定向到/login

Looking good! In the next sections, we will register our application with the social network providers so that users can be authenticated via social platforms.

看起来不错! 在下一部分中,我们将在社交网络提供商中注册我们的应用程序,以便可以通过社交平台对用户进行身份验证。

Facebook认证 ( Facebook Authentication )

In this section, we will do the heavy lifting and set up authentication via Facebook.

在本节中,我们将进行繁重的工作并通过Facebook设置身份验证。

获取Facebook凭证 (Get Facebook Credentials)

Head over to the Facebook Developers’ page, after signing in, click on Add a New App and enter the details for the app on the modal window that appears:

登录后,转到Facebook开发人员页面 ,单击“ 添加新应用” ,然后在出现的模式窗口中输入该应用的详细信息:

Once the app has been created, you will be redirected to the application’s dashboard. On the left side of the screen, click on** Settings
, then click on the **Basic option that appears directly underneath it.

,然后点击直接出现在其下方的**基本选项。

When the new screen loads, under the App Domains section, add localhost like this:

加载新屏幕后,在“ 应用程序域”部分下,添加localhost如下所示:

Now scroll down until you see an option that says Add Platform, Click on it and select the Website option. This will create a website section where you will see Site URL, add http://localhost:8000/ in the input and click on the Save Changes button:

现在向下滚动,直到看到显示“ 添加平台”的选项,单击它并选择“ 网站”选项。 这将创建一个网站部分,您将在其中看到“ 网站URL” ,在输入中添加http://localhost:8000/ ,然后单击“ 保存更改”按钮:

Now, copy the App ID and App secret from the applications dashboard and add them to the settings.py file:

现在,从应用程序仪表板复制App ID和App secret并将它们添加到settings.py文件中:

# social_app/settings.py

    #[...]

    SOCIAL_AUTH_FACEBOOK_KEY = YOUR_APP_KRY        # App ID
    SOCIAL_AUTH_FACEBOOK_SECRET = YOUR_APP_SECRET  # App Secret

    #[...]

Replace the YOUR_APP_* keys with the values from your Facebook application dashboard.

用Facebook应用程序仪表板中的值替换YOUR_APP_ *键。

Let’s update the URL of the Login with Facebook button in login.html file with this one:

让我们用以下命令更新login.html文件中“使用Facebook登录”按钮的URL

<!-- templates/login.html -->

            <button class="btn btn-primary mb-2">
                <a href="{% url 'social:begin' 'facebook' %}">Login with Facebook</a>
            </button>

Start up the web server and visit localhost:8000/login to test that we can now log into the application via Facebook:

启动Web服务器并访问localhost:8000/login以测试我们现在可以通过Facebook登录到该应用程序:

(django_social_app) $ python manage.py runserver

Note: You need to be in the parent social_app directory to run ‘python manage.py *’ commands.

注意:您需要在父social_app目录中运行“ python manage.py *”命令。

When we click on the Login with Facebook button, we should be redirected to a page similar to the one below:

当我们单击“ 使用Facebook登录”按钮时,我们应该被重定向到与以下页面相似的页面:

Clicking on Continue as USERNAME will redirect to the home page and your username will be displayed. We have successfully been authenticated via Facebook:

单击以USERNAME身份继续的操作将重定向到主页,并显示您的用户名。 我们已经通过Facebook成功通过了身份验证:

Want to know what just happened behind the scenes? Let’s find out; we will create a superuser account to access the admin panel:

(django_social_app) $ python manage.py createsuperuser

You will get a prompt to enter a username, email and password for the superuser. Be sure to enter details that you can remember because you will need them to log in to the admin dashboard shortly.

您将提示输入超级用户的用户名,电子邮件和密码。 确保输入您可以记住的详细信息,因为您将需要它们很快登录到管理仪表板。

After creating the superuser account, we will run the server and visit the admin panel on this address — http://localhost:8000/admin/:

创建超级用户帐户后,我们将运行服务器并访问该地址上的管理面板-http:// localhost:8000 / admin /

We can see that a new User (besides the superuser) has been created in the
Users category:

用户”类别中已经创建了一个新用户(超级用户除外):

We will also see that there is a new account under the User social auths category:

我们还将看到“ 用户社交身份验证”类别下有一个新帐户:

The explanation for the existence of these new accounts is: When a user logs into the application using Facebook (or any social network provider), a new User and User Social Auth instance are created. The User Social Auth is linked to the User account the first time, then subsequently, the User instance is simply queried from the database.

这些新帐户的存在的解释是:当用户使用Facebook(或任何社交网络提供商)登录应用程序时,将创建一个新的UserUser Social Auth实例。 第一次将User Social Auth链接到User帐户,然后,仅从数据库中查询User实例。

The User instance is created using the details received from the social network provider. In this case, Facebook sent back the first_name and last_name fields of the created User Instance, and the username is a concatenation of the first_name and last_name.

使用从社交网络提供商接收的详细信息创建用户实例。 在这种情况下,Facebook发回了创建的用户实例的first_namelast_name字段,而用户名是first_namelast_name的串联。

Some social providers (like Instagram) will return the user’s username on their platform and this is used (instead of the concatenation) for the created User instance on the application.

一些社交提供程序(如Instagram)将在其平台上返回用户的用户名,并且该用户名(而非串联)用于应用程序上创建的User实例。

We don’t want our application to just display a username, we want to get additional *User *data such as profile picture, so let’s request for extra data from Facebook.

我们不希望我们的应用程序仅显示用户名,我们希望获取其他* 用户*数据,例如个人资料图片,因此让我们向Facebook请求额外的数据。

Note: You will need to log out from the admin panel to continue.

注意:您需要从管理面板注销才能继续。

Open the settings.py file and update it accordingly:

打开settings.py文件并进行相应更新:

# settings.py

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                    'social_django.context_processors.backends', # add this
                    'social_django.context_processors.login_redirect', # add this
                ],
            },
        },
    ]

    SOCIAL_AUTH_FACEBOOK_KEY = YOUR_APP_SECRET          # App ID
    SOCIAL_AUTH_FACEBOOK_SECRET = YOUR_APP_SECRET       # App Secret
    SOCIAL_AUTH_FACEBOOK_SCOPE = ['email', 'user_link'] # add this
    SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = {       # add this
      'fields': 'id, name, email, picture.type(large), link'
    }
    SOCIAL_AUTH_FACEBOOK_EXTRA_DATA = [                 # add this
        ('name', 'name'),
        ('email', 'email'),
        ('picture', 'picture'),
        ('link', 'profile_url'),
    ]

Replace the YOUR_APP_* keys with the values from your Facebook application dashboard.

用Facebook应用程序仪表板中的值替换YOUR_APP_ *键。

The social_django context processors help in adding backend and associations data to template context. This makes it easy for us to access data about the authenticated user using template tags. You can read more about it here.

social_django上下文处理器有助于将后端数据和关联数据添加到模板上下文中。 这使我们可以轻松地使用模板标签访问有关已认证用户的数据。 您可以在此处了解更多信息。

When a user logs into the application via Facebook, we can access a subset of the user’s data using permissions; permissions are how we ask if we can access the data on Facebook. In the code above, SOCIAL_AUTH_FACEBOOK_SCOPE contains a list of permissions to access the data properties our application requires. The email and user_link permissions request access to the user’s Facebook email and profile link respectively.

当用户通过Facebook登录该应用程序时,我们可以使用权限访问该用户数据的一部分。 权限是我们询问是否可以访问Facebook上的数据的方式。 在上面的代码中, SOCIAL_AUTH_FACEBOOK_SCOPE包含访问应用程序所需数据属性的权限列表。 email和user_link权限分别请求访问用户的Facebook电子邮件和个人资料链接。

Let’s start the server now, visit http://localhost:8000/login/, and attempt logging in via Facebook:

让我们现在启动服务器,访问http:// localhost:8000 / login / ,然后尝试通过Facebook登录:

Clicking on Continue as USERNAME will grant the application access to user’s private data on Facebook and for this reason, to request for some permissions, you will need to submit your application to be reviewed by the Facebook team to ensure that the returned data isn’t misused. You can find the list of Facebook permissions here.

单击“继续以USERNAME身份登录”将授予应用程序访问Facebook上用户的私人数据的权限,因此,要请求一些权限,您需要提交应用程序以供Facebook团队审查,以确保返回的数据不存在被滥用。 您可以在此处找到Facebook权限列表

SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS has a key — fields — where the value is a list of attributes that should be returned by Facebook when the user has successfully logged in. The values are dependent on SOCIAL_AUTH_FACEBOOK_SCOP .

SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS有一个键- fields -其中的值是用户成功登录后Facebook应该返回的属性列表。这些值取决于SOCIAL_AUTH_FACEBOOK_SCOP

When a user logs in using Facebook, the Facebook API returns the data requested in SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS. To store the data in the database, we need to specify them in SOCIAL_AUTH_FACEBOOK_EXTRA_DATA.

当用户使用Facebook登录时,Facebook API返回在SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS请求的数据。 要将数据存储在数据库中,我们需要在SOCIAL_AUTH_FACEBOOK_EXTRA_DATA指定它们。

The extra data will be stored in the extra_datafield of the User Social Auth instance:

多余的数据将存储在User Social Auth实例的extra_data字段中:

Now, let’s update the frontend to display the extra data we received from Facebook, we will open the
home.html file and replace its content with this one:

home.html文件并将其内容替换为以下内容:

<!-- home.html -->

    {% extends 'base.html' %}
    {% block title %} Home {% endblock %}
    {% block content %}
      <div class="row">
        <div class="col-sm-12 mb-3">
          <h4 class="text-center">Welcome {{ user.username }}</h4>
        </div>

            <!-- Add from here -->
        {% for ass in backends.associated %}
          {% if ass.provider == 'facebook' %}
            <div class="col-md-6 text-center">
                <img src="{{ass.extra_data.picture.data.url}}" alt="" width="150" height="150" style="border-radius: 50%">
            </div>
            <div class="col-md-6 social-container my-2">                 <p> Signed in via:  {{ ass.provider }} </p>
                <p> Name:  {{ ass.extra_data.name }} </p>
                <p> Provider url: <a href="{{ass.extra_data.profile_url}}">link</a></p>
            </div>
          {% endif %}
        {% endfor %}
        <div class="col-sm-12 mt-2 text-center">
          <button class="btn btn-danger">
            <a href="{% url 'logout' %}">Logout</a>
          </button>
        </div>
            <!-- End here -->
      </div>
    {% endblock %}

Now we can visit the application’s home address — http://localhost:8000/ — on a web browser and see the extra data:

现在,我们可以在网络浏览器上访问应用程序的家庭地址— http:// localhost:8000 / ,并查看其他数据:

Note: We now have access to the data that gets stored in the `extra_data` field because we added the context processors to `TEMPLATES`; this enables us to access `backends` data in the frontend.

注意:现在我们可以访问存储在`extra_data`字段中的数据,因为我们将上下文处理器添加到了'TEMPLATES'中。 这使我们能够访问前端中的“后端”数据。

Congratulations! we have successfully authenticated via Facebook and can now move on to setting up the next social network provider.

恭喜你! 我们已经通过Facebook成功进行了身份验证,现在可以继续建立下一个社交网络提供商了。

Instagram认证 ( Instagram Authentication )

Seeing that we’ve gone into details on how things work behind the scene, we can set up the Instagram authentication in just three steps:

看到我们已经详细了解了幕后工作原理,我们可以通过三个步骤来设置Instagram身份验证:

  • Get API credentials

    获取API凭证

  • Setup the backend

    设置后端

  • Setup the frontend

    设置前端

Let’s go!

我们走吧!

获取API凭证 (Get API credentials)

Let’s visit the Instagram developers page and click on Register Your Application:

让我们访问Instagram开发人员页面 ,然后单击“ 注册您的应用程序”:

On the screen that comes up next, click on Register a New Client and fill out the details for the application:

在接下来出现的屏幕上,单击注册新客户端,然后填写该应用程序的详细信息:

Note: Instagram (and most social network providers) require a redirect URL which will be the address the user’s browser will be directed to after the authentication. For this tutorial, we will use this address http://localhost:8000/social-auth/complete/instagram/. You can learn more about this here.

注意:Instagram(和大多数社交网络提供商)需要重定向URL,该URL将是身份验证后用户浏览器将定向到的地址。 对于本教程,我们将使用此地址http:// localhost:8000 / social-auth / complete / instagram / 。 您可以在此处了解更多信息。

Successful registration of the application will return a screen like this:

成功注册该应用程序将返回如下屏幕:

Now, we will click on the
Manage option to get the application’s Client ID and Client Secret:

管理选项以获取应用程序的客户端ID和客户端密钥:

Note: We need the ID and the Secret to configure the backend.

注意:我们需要ID和密码来配置后端。

设置后端 (Setup the Backend)

Let’s add this code to the settings.py file:

让我们将此代码添加到settings.py文件中:

# settings.py

    #[...]

    # add this code
    SOCIAL_AUTH_INSTAGRAM_KEY = YOUR_CLIENT_ID         #Client ID
    SOCIAL_AUTH_INSTAGRAM_SECRET = YOUR_CLIENT_SECRET  #Client SECRET
    SOCIAL_AUTH_INSTAGRAM_EXTRA_DATA = [         ('user', 'user'),
    ]

    #[...]

Replace the YOUR_CLIENT_* keys with the values from your Instagram application.

将YOUR_CLIENT_ *键替换为Instagram应用程序中的值。

With the code above, once a user is authenticated via Instagram, a user object will be sent back to the application. We add this object to SOCIAL_AUTH_INSTAGRAM_EXTRA_DATA because we want it to be stored in the database for easy reference.

使用上面的代码,一旦通过Instagram对用户进行身份验证, user对象将被发送回应用程序。 我们将此对象添加到SOCIAL_AUTH_INSTAGRAM_EXTRA_DATA因为我们希望将其存储在数据库中以便于参考。

The user object is returned in this format:

user对象以以下格式返回:

{
      "id": ...,
      "username": ...,
      "profile_picture": ...,
      "full_name": ...,
      "bio": ...,
      "website": ...,
      "is_business": ...,
    }

设置前端 (Setup the Frontend)

We want to display a nice UI for when a user is authenticated via Instagram so let’s replace the content of the home.html file with the code below:

当用户通过Instagram进行身份验证时,我们希望显示一个漂亮的UI,因此让我们用以下代码替换home.html文件的内容:

<!-- home.html -->

    {% extends 'base.html' %}
    {% block title %} Home {% endblock %}
    {% block content %}
    <div class="row">
        <div class="col-sm-12 mb-3">
            <h4 class="text-center">Welcome {{ user.username }}</h4>
        </div>
        <!-- Add from here -->
        {% for ass in backends.associated %}
          {% if ass.provider == 'facebook' %}
            <div class="col-md-6 text-center">
                <img src="{{ass.extra_data.picture.data.url}}" alt="" width="150" height="150" style="border-radius: 50%">
            </div>
            <div class="col-md-6 social-container my-2">                 <p> Signed in via:  {{ ass.provider }} </p>
                <p> Name:  {{ ass.extra_data.name }} </p>
                <p> Provider url: <a href="{{ass.extra_data.profile_url}}">link</a></p>
            </div>
          {% endif %}
          <!-- Add from here -->
          {% if ass.provider == 'instagram' %}
            <div class="col-md-6 text-center">               <img src="{{ ass.extra_data.user.profile_picture }}" alt="" width="150" height="150" style="border-radius: 50%">             </div>
            <div class="col-md-6 social-container my-2">
              <p>Signed in via: {{ ass.provider }} </p>
              <p> Name:  {{ ass.extra_data.user.full_name }} </p>
              <p>Provider url: <a href="https://instagram.com/{{ ass.username }}">link</a></p>
          {% endif %}
          <!-- End here -->
        {% endfor %}
        <div class="col-sm-12 mt-2 text-center">
            <button class="btn btn-danger">
                <a href="{% url 'logout' %}">Logout</a>
            </button>
        </div>
        <!-- End here -->
    </div>
    {% endblock %}

Let’s update the URL of the *Login with Instagram *button in login.html file:

让我们更新login.html文件中* 使用Instagram登录*按钮的URL

<!-- templates/login.html -->

        <button class="btn btn-danger  mb-2">
            <a href="{% url 'social:begin' 'instagram' %}">Login with Instagram</a>
        </button>

We can now start the server, visit http://localhost:8000/login, and try to login with Instagram:

我们现在可以启动服务器,访问http:// localhost:8000 / login ,并尝试使用Instagram登录:

Note: The Instagram application is in sandbox (test) mode. To make it live, you will have to submit it for a review. You can learn more about this here.

注意:Instagram应用程序处于沙箱(测试)模式。 要使其生效,您必须将其提交以进行审核。 您可以在此处了解更多信息。

Once the application is authorized, the user will be logged in and redirected to the home page:

授权应用程序后,用户将登录并重定向到主页:

Linkedin认证 ( Linkedin Authentication )

We will set up LinkedIn authentication in three steps:

我们将通过三个步骤设置LinkedIn身份验证:

  • Get API credentials

    获取API凭证

  • Setup the Backend

    设置后端

  • Setup the Frontend

    设置前端

获取API凭证 (Get API credentials)

Let’s visit the Linkedin developers page and click on Create app:

让我们访问Linkedin开发人员页面 ,然后点击创建应用

Fill out the application details:

Note: Most of these fields are required and you will have to fill them out with valid structured data.

注意:这些字段中的大多数是必填字段,您必须使用有效的结构化数据填写它们。

Once the app has successfully been created, you will be redirected to the application’s dashboard. Here, add http://localhost:8000/social-auth/complete/linkedin-oauth2/ as the redirect URL and update the application:

成功创建应用程序后,您将被重定向到应用程序的仪表板。 在这里,添加http:// localhost:8000 / social-auth / complete / linkedin-oauth2 /作为重定向URL并更新应用程序:

Take note of the Client ID and Secret, we will need it in setting up the backend.

注意客户端ID和密钥,在设置后端时将需要它。

设置后端 (Setup the Backend)

Let’s add this code to the settings.pyfile:

让我们将此代码添加到settings.py文件中:

# settings.py

    #[...]

    # add this code
    SOCIAL_AUTH_LINKEDIN_OAUTH2_KEY = YOUR_CLIENT_ID         #Client ID
    SOCIAL_AUTH_LINKEDIN_OAUTH2_SECRET = YOUR_CLIENT_SECRET  #Client Secret
    SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE = ['r_basicprofile', 'r_emailaddress']
    SOCIAL_AUTH_LINKEDIN_OAUTH2_FIELD_SELECTORS = ['email-address', 'formatted-name', 'public-profile-url', 'picture-url']
    SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA = [
        ('id', 'id'),
        ('formattedName', 'name'),
        ('emailAddress', 'email_address'),
        ('pictureUrl', 'picture_url'),
        ('publicProfileUrl', 'profile_url'),
    ]

    #[...]

Replace the YOUR_CLIENT_* keys with the values from your LinkedIn application.

用LinkedIn应用程序中的值替换YOUR_CLIENT_ *键。

The SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE array contains the permissions needed to access the user’s data, similar to what we saw when we set up authentication via Facebook.

SOCIAL_AUTH_LINKEDIN_OAUTH2_SCOPE数组包含访问用户数据所需的权限,类似于我们通过Facebook设置身份验证时看到的权限。

The SOCIAL_AUTH_LINKEDIN_OAUTH_FIELD_SELECTORS array contains the list of data that should be returned when the user is successfully authenticated via Linkedin. It is similar to the SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS array for Facebook. You can find the full list of data items that can be requested for here.

SOCIAL_AUTH_LINKEDIN_OAUTH_FIELD_SELECTORS数组包含当用户通过Linkedin成功通过身份验证时应返回的数据列表。 它类似于Facebook的SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS数组。 您可以在此处找到可请求的数据项的完整列表

The SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA array contains the data that we want to store in the database for later reference.

SOCIAL_AUTH_LINKEDIN_OAUTH2_EXTRA_DATA数组包含我们要存储在数据库中以供以后参考的数据。

设置前端 (Setting up Frontend)

Let’s replace the content of the home.html file with the code below:

让我们用以下代码替换home.html文件的内容:

<!-- home.html -->

    {% extends 'base.html' %}
    {% block title %} Home {% endblock %}
    {% block content %}
    <div class="row">
        <div class="col-sm-12 mb-3">
            <h4 class="text-center">Welcome {{ user.username }}</h4>
        </div>
        <!-- Add from here -->
        {% for ass in backends.associated %}
          {% if ass.provider == 'facebook' %}
            <div class="col-md-6 text-center">
                <img src="{{ass.extra_data.picture.data.url}}" alt="" width="150" height="150" style="border-radius: 50%">
            </div>
            <div class="col-md-6 social-container my-2">                 <p> Signed in via:  {{ ass.provider }} </p>
                <p> Name:  {{ ass.extra_data.name }} </p>
                <p> Provider url: <a href="{{ass.extra_data.profile_url}}">link</a></p>
            </div>
          {% endif %}
          {% if ass.provider == 'instagram' %}
            <div class="col-md-6 text-center">               <img src="{{ ass.extra_data.user.profile_picture }}" alt="" width="150" height="150" style="border-radius: 50%">             </div>
            <div class="col-md-6 social-container my-2">
              <p>Signed in via: {{ ass.provider }} </p>
              <p> Name:  {{ ass.extra_data.user.full_name }} </p>
              <p>Provider url: <a href="https://instagram.com/{{ ass.username }}">link</a></p>
          {% endif %}
          <!-- Add from here -->
          {% if ass.provider == 'linkedin-oauth2' %}
            <div class="col-md-6 text-center">
                <img src="{{ass.extra_data.picture_url}}" alt="" width="150" height="150" style="border-radius: 50%">
            </div>
            <div class="col-md-6 social-container my-2">                 <p> Signed in via:  Linkedin </p>
                <p> Name:  {{ ass.extra_data.name }} </p>
                <p> Provider url: <a href="{{ass.extra_data.profile_url}}">link</a></p>
            </div>
          {% endif %}
          <!-- End here -->
        {% endfor %}
        <div class="col-sm-12 mt-2 text-center">
            <button class="btn btn-danger">
                <a href="{% url 'logout' %}">Logout</a>
            </button>
        </div>
        <!-- End here -->
    </div>
    {% endblock %}

We will also update the URL of the Login with LinkedIn button in the login.html file:

我们还将在login.html文件中更新“ 使用LinkedIn登录”按钮的URL

<!-- templates/login.html -->

        <button class="btn btn-info mb-2">
           <a href="{% url 'social:begin' 'linkedin-oauth2' %}">Login with LinkedIn</a>
        </button>

We can now start the server, visit http://localhost:8000/login, and try to login with LinkedIn:

现在,我们可以启动服务器,访问http:// localhost:8000 / login ,然后尝试使用LinkedIn进行登录:

Once we authorize the application by clicking on
Allow, we will be directed to the homepage:

Allow来授权应用程序后,我们将转到首页:

结论 ( Conclusion )

We have come to the end of this tutorial and have learnt how to set up social authentication in Django using the social-auth-app-django library with minimal configuration. We have also learnt how to request extra user data once the user has been authenticated via a social network provider.

我们已经到了本教程的结尾,并且学习了如何使用social-auth-app-django库以最小的配置在Django中设置社交身份验证。 我们还学习了通过社交网络提供商对用户进行身份验证后,如何请求其他用户数据。

As we already discussed at the beginning of this article, the importance of social authentication in modern web applications cannot be overemphasized.

正如我们在本文开头所讨论的那样,在现代Web应用程序中社交身份验证的重要性不可过分强调。

The code for this article is available here on GitHub.

本文的代码可以在这里 GitHub上。

翻译自: https://scotch.io/tutorials/django-authentication-with-facebook-instagram-and-linkedin

instagram css

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值