pythondjangomicrosoft-graph-apidjango-authenticationazure-authentication

How to setup Microsoft authentication in a django based project


I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with Microsoft authentication page. It will be great if someone can tell me how to do this. You can see this picture. Here Microsoft button is automatically added for login. How to set up a button like this on the home page?


Solution

  • 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.

    Firstly you should walk-through the given tutorial then you can easily understand the code given below.

    In the given tutorial they authenticate the user using sessions. I find the Django authentication handier so I just edited callback and signout function as per given below.

    Here I'm writing only callback and signout function.

    How my problem solved: now I can simply change the sign-in URL in urls.py file. If I want to set a button with a login page I can simply use an anchor element referring to sign-in 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')