如何在基于 Django 的项目中设置 Microsoft 身份验证

How to setup Microsoft authentication in a django based project

我在我的 Django 项目中使用 django-microsoft-auth。我关注了 this guide. 现在,我可以通过 Microsoft 帐户(地址:http://localhost:8000/admin )登录,但我不知道如何添加显示 "Login using Microsoft" 的视图以及如何 link 该视图带有 Microsoft 身份验证页面。 如果有人能告诉我如何做到这一点,那就太好了。 你可以看到 this 图片。此处会自动添加用于登录的 Microsoft 按钮。如何在首页设置这样的按钮?

I found a handy way for Microsoft authentication. I used the Microsoft graph. There is well-written documentation for Microsoft Graph. you can refer to this here. You can ignore the calendar part if you are only interested in the authentication part.

首先你应该通过给定的教程,然后你可以很容易地理解下面给出的代码。

在给定的教程中,他们使用会话对用户进行身份验证。我发现 Django 身份验证更方便,所以我只是按照下面给出的方式编辑了回调和注销函数。

这里我只写了回调函数和注销函数。

我的问题是如何解决的:现在我可以简单地更改 urls.py 文件中的登录 URL。如果我想设置一个带有登录页面的按钮,我可以简单地使用一个引用登录的锚元素 URL.

    def callback(request):
      # Get the state saved in session
      expected_state = request.session.pop('auth_state', '')
      # Make the token request
      token = get_token_from_code(request.get_full_path(), expected_state)
      # Get the user's profile
      user = get_user(token)

      # Get user info
      # user attribute like displayName,surname,mail etc. are defined by the 
      # institute incase you are using single-tenant. You can get these 
      # attribute by exploring Microsoft graph-explorer.

      username = user['displayName']
      password = user['surname']
      email = user['mail']

      try:
          # if use already exist
          user = User.objects.get(username=username)

      except User.DoesNotExist:
          # if user does not exist then create a new user
          user = User.objects.create_user(username,email,password)
          user.save()

      user = authenticate(username=username,password=password)

      if user is not None:
          login(request,user)
          messages.success(request,"Success: You were successfully logged in.")
          return redirect('home')
      return redirect('home')

    def sign_out(request):

      logout(request)
      messages.success(request, "Successfully Logged Out")

      return redirect('home')