GithubHelp home page GithubHelp logo

microsoftgraph / msgraph-sample-pythondjangoapp Goto Github PK

View Code? Open in Web Editor NEW
123.0 123.0 63.0 1.14 MB

This sample demonstrates how to use the Microsoft Graph .NET SDK to access data in Office 365 from Python web apps.

License: MIT License

Python 76.38% CSS 0.75% HTML 22.87%
devxsample

msgraph-sample-pythondjangoapp's People

Contributors

dependabot[bot] avatar dodaromike avatar github-actions[bot] avatar jasonjoh avatar microsoft-github-policy-service[bot] avatar msftbot[bot] avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sample-pythondjangoapp's Issues

POST requests? Django + microsoft graph

I have been able to successfully run the tutorial code with GET requests. Now I wish to make POST requests with a graph_client.post(https://graph.microsoft.com/v1.0/users, data={'userPrincipalName': '[email protected]', etc... }) type of construction. Unfortunately, this generates a HTTP 400 message of the form 'code': 'BadRequest', 'message': 'Entity only allows writes with a JSON Content-Type header.'. Will the tutorial constructs work with POST requests?

If you can guide me on where to add the lines to make a POST method work successfully. I am attaching screenshots of my code please find below:-

HTML page:-
1

views.py:-
2

graph_helper.py;-
3

Syntax Error on Raise From in Manage.py because of the shebang line?

I'm getting a syntax error on the raise ImportError line in manage.py because of the shebang line

File ".\manage.py", line 12
raise ImportError("Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?" ) from exc

I messed a bit with the error line while I was trying to figure out what was wrong.

If I remove
#!/usr/bin/env python
it doesn't seem to get a syntax error.

Help?

May need to import render

I've tried a tutorial "Build Python Django apps with Microsoft Graph".
Then I found that I needed an additional code at last section in step "Create a Python Django web app".

I added a below line in top of ./tutorial/views.py .

from django.shortcuts import render

If needed please confirm this.

Thank you for your great tutorial.

OWA graph simple example required - no django

I am researching how to add calendar support to one of my projects.

This tutorial is asking that I know django before I can untangle the logic of talking to graph.
I do not know django so that is making this tutorial unhelpful.

Do you have a tutorial that is a simple command line that just shows the use of the API?

Sign in does not work

Where did you get the code?

Describe the bug

When you click sign in you get an error The input scopes should be a list, tuple, or set

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'main page'
  2. Click on 'sign in'
  3. See error

Expected behavior

It should give you prompt to authenticate you with Microsoft account

Screenshots

If applicable, add screenshots to help explain your problem.
image

Tutorial part 3: Sign-In throws error - localhost refused to connect.

Where did you get the code?

Describe the bug

Intead of being redirected to microsoft login, the browser shows a page with an error:
localhost refused to connect.

To Reproduce

Steps to reproduce the behavior:

Follow step by step through the tutorial. Upon reaching part 7 of page 3 - user signin - where it says "Start the server and browse to https://localhost:8000. Click the sign-in button and you should be redirected to https://login.microsoftonline.com. Login with your Microsoft account and consent to the requested permissions. The browser redirects to the app, showing the response, including the access token."

Expected behavior

the be redirected to login.microsoftonline.com as described in tutoiral

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: WINDOWS 10
  • Browser chrome, firefox

Quickstart Fails to Authenticate.

Where did you get the code?

Describe the bug

Unable to authenticate against an Azure Tenant - [email protected]
Works fine with personal MS accounts

To Reproduce

Steps to reproduce the behavior:

Followed the quickstart and it auto-generated the application and created the Key and Secret in the YML file. Unzipped the file. Created a virtual environment, ran pip install -r requirements.txt to install the version as required. Python manage.py migrate and then python manage.py runserver.
Went directly to the home page http://localhost:8000 and got presented with the branded login screen. Clicked Sign and got redirected to MS Login screen. Entered the username, password got prompted for my MS Authenticator to approve the login. Following the approval, I accepted the application permissions and got redirected back to the home page. The server console shows the /signin HTTP/1.1 302 0 and following the acceptance of the application permissions I see the console with the /callback?code=0.AAVAAQCX{....} etc. But i do not see the authenticated Nav Bar items. As a test of my authentication, I went to the /calendar route and it too errored with a line 75, in calendar time_zone = get_iana_from_windows(user['timeZone']) which is unrelated to the auth error. But the user vars on the debug page show

{'user': {'is_authenticated': False}}
request | <WSGIRequest: GET '/calendar'>
user | {'is_authenticated': False}

So I can tell I am not authenticated. I attempted the /signout route and the console reports /signout HTTP/1.1 302 and I am redirected to the default route "/"

This is a Micosoft E5 developer account just created.
SUbsequent requests to not prompt for app permissions but still go through the authenticator but still fail.

(note: I tried to access the app with my personal MS account not part of the tenant and the app worked as expected)

Expected behavior

I would expect that when I hit sign in and approve when authenticating against an Azure Tenant the same way it would against a personal account.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Dependency versions

asgiref==3.3.4
certifi==2020.12.5
cffi==1.14.5
chardet==4.0.0
cryptography==3.4.6
Django==3.2
idna==2.10
msal==1.10.0
pycparser==2.20
PyJWT==2.0.1
python-dateutil==2.8.1
pytz==2021.1
PyYAML==5.4.1
requests==2.25.1
six==1.15.0
sqlparse==0.4.1
urllib3==1.26.4

Additional context

The default dev E5 tenant is locked down pretty tight with security by default. I just created this tenant last week.
I also tried to follow the Tutorial and typed all the data in myself but that yielded the same results. I initially though the error was mine but when I downloaded the quickstart and thirdly the git repo and ALL 3 methods produced the same results. I suspect this is a permission or scope issue

settings.py needs to be updated for templates and static folders

Where did you get the code?

Describe the bug

A clear and concise description of what the bug is.

Tutorial creates the folders tutorial/templates/tutorial and tutorial/static/tutorial. Instructions for updating settings.py to see content placed in these folders is not included in tutorial steps. This could prevent someone who is new to Django from being able to complete the tutorial.

To Reproduce

Steps to reproduce the behavior:

Follow the first section of the tutorial, 'Create a Python Django Web App'

Expected behavior

Expected home page to load.

Screenshots

django.template.exceptions.TemplateDoesNotExist

Desktop

  • OS: MacOS
  • Browser edge, Firefox, safari
  • Version 11.2.1

Dependency versions

  • Authentication library (MSAL, etc.) version: 1.7.0
  • Graph library (Graph SDK, REST library, etc.) version:

Additional context

The following settings will resolve the TemplateDoesNotExist issue:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [(BASE_DIR / 'tutorial/templates/'),],
            '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',
                ],
            },
        },
    ]
    
    STATICFILES_DIRS = [
        (BASE_DIR / "tutorial/static/"),
    ]

关于权限更新的故障

我按照本教程一步步搭建项目并且大部分完成,但到了最后访问日历的时候,需要新的权限(日历),但我的账户在注册应用时并没有授予日历权限,导致最终不能获取到日历数据。在我更换另外的Microsoft账户登陆并授权后,新的账户是正常使用的

Unauthenticated User Exception

Where did you get the code?

Describe the bug

Unauthenticated attempt to access localhost:8000/calendar directly generates a traceback line 75 in views.py
time_zone = get_iana_from_windows(user['timeZone'])
This makes sense as the there is no way to grab the user session for TZ

To Reproduce

Steps to reproduce the behavior:

  1. Navigate to localhost:8000
  2. Do NOT log in
  3. append /calendar to the url --> http://localhost:8000/calendar
  4. Error appears

Expected behavior

I would thing there is or should be an is authenticated check in the view and if not it would redirect back to the home page.
Is there a way to implement that in views.py as opposed to the hard coding it in the HTML page. Some sort of decorator applied to the def calendar(request). Not sure @login_required would work here since we are using msal vs the default django system?? Or would user_passes_test be an option. (https://www.adamsmith.haus/python/docs/django.contrib.auth.decorators.user_passes_test)
I would like to implement it myself in the code but I am not that smart and just learning from these tutorials

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

OS - Windows 10 64bit
Browser - Chrome
Version - 99.0.4844.51

Dependency versions

  • Authentication library msal==1.10.0
  • Graph library (Graph SDK, REST library, etc.) version:

Additional context

Maybe this falls under feature request but was hoping it was an easy addition to the code

ValueError ("state missing from auth_code_flow")

Thank you for taking an interest in Microsoft Graph development! Please feel free to ask a question here, but keep in mind the following:

  • This is not an official Microsoft support channel, and our ability to respond to questions here is limited. Questions about Graph, or questions about adding a new feature to the sample, will be answered on a best-effort basis.
  • Questions should be asked on Stack Overflow.
  • Issues with Microsoft Graph itself should be handled through support.

I'm attempting to implement a login to my Web App where users are able to login to my web app using their microsoft account details. I have configured my app on the azure portal and have noted down the secret keys and app ids. After running my web app using "python manage.py runserver", it loads up the login page but when I click the login button it shows me the error ValueError ("state missing from auth_code_flow") I'm unsure on what I have done wrong as I'm quite new to this.

Below is the traceback for the error:

`Environment:

Request Method: GET
Request URL: http://localhost:8000/callback?code=0.AVUAegPvFePt6069AkzKAhoHDjNEpBDc_VVGhzU85c_vy4tVAKM.AQABAAIAAAD--DLA3VO7QrddgJg7WevrjcZwonGw5nbgUqKFrxqdChsY4GcXNN8nsrvQMbcX7al1AM1K6EXRE3geLEAYqf734wHnjtvS9-7U_Pl82LQNe7LmeWFIe76oTPkIxI9eHrV9QdBPbRi2hxlVpl9cq5P9Od6xnAZdpTpvMA6vLsu--EGpRYUyoMTdY6zJvSH-IRJqV0Mc6o9lI1ZsMOGchSiNtXCui_eFolQEXBvWFdB6Wk3uPu7vcwFEpydYsI8Crhoynyo6gxezTatdIMchd4yReLtLeTLG4hoef5MMd3h7AXEwa-1W08C-nzN_5YSTB3GNVW6Ymxrv4lkleAnHxMltDf_EPzIAllcuGeUs3qLB3areZhqtTLK-sAPczegT7-nRxlrmgZ5tvftxQMbOqx7qycVBqybMRXlrVqa0PeKIClD1ZtrpO_g1qO_fq_ztwQAkSpyXQgE8VGkVTlw_XCEfsOB10DOkkfbf7GX_iLbfBzBP6pGniEpIhlgIEpY26TLq3SztX2L1ZaU5QT_wOAXn_zIL1B5DGfd6GeFGPo4DaAdGh3k4-Zn6f9a0OWVdJfd7ZHMMFjWRzIvx8P0xJizDH6xRidHNsOSN7ibdBPlNmHMlcVtLBWRfcRTDQw1Nvb6Ui81L7pUOzCisc9LsLAASGp9gnRPErnGt6CcuaN3Vb1nf3XIUHdbt3toKYCeAkUM5lU2CEBX0NR7Mlp02e997hHAQdxZvkS3-PgTXYO6gX0gR8sLUrmyuvtI2tl7c-DnhGeqN7UdwU7pZDhqn6hZL7aHtNh8MiwXar4Yej_m1_uotLiSkgx25GzgHZ9q76YuVhhHKb7k9bdFhKDCJEwzPM1inTS2MbBo60ft6CwGI4CAA&state=qyiDpQSuHoMKWznN&session_state=0e1d1c16-928e-4e6f-a584-94f70c4fb91c

Django Version: 3.0.5
Python Version: 3.9.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ClaimsWebsite.apps.ClaimswebsiteConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Muhammad.ariffin\Desktop\Workspace\Django_Website\ClaimsWebsite\views.py", line 68, in callback
result = get_token_from_code(request)
File "C:\Users\Muhammad.ariffin\Desktop\Workspace\Django_Website\ClaimsWebsite\auth_helper.py", line 50, in get_token_from_code
result = auth_app.acquire_token_by_auth_code_flow(flow, request.GET)
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\msal\application.py", line 513, in acquire_token_by_auth_code_flow
return self.client.obtain_token_by_auth_code_flow(
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\msal\oauth2cli\oidc.py", line 185, in obtain_token_by_auth_code_flow
result = super(Client, self).obtain_token_by_auth_code_flow(
File "C:\Users\Muhammad.ariffin\AppData\Local\Programs\Python\Python39\lib\site-packages\msal\oauth2cli\oauth2.py", line 538, in obtain_token_by_auth_code_flow
raise ValueError("state missing from auth_code_flow")

Exception Type: ValueError at /callback
Exception Value: state missing from auth_code_flow`

Auto-Generated Quickstart fails with Python 2.7.17 pip 9.0.1 on WSL

Microsoft Graph Quick Start - Python (link)

Expected: pip command on un-modified generated requirements.txt installs

Actual: pip command fails with error message
Collecting asgiref==3.2.7 (from -r requirements.txt (line 1)) Could not find a version that satisfies the requirement asgiref==3.2.7 (from -r requirements.txt (line 1)) (from versions: 0.8, 0.9, 0.9.1, 0.10.0, 0.11.0, 0.11.1, 0.11.2, 0.12.0, 0.12.1, 0.13.0, 0.13.2, 0.13.3, 0.14.0, 1.0.0, 1.0.1, 1.1.0, 1.1.1, 1.1.2, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.1.2, 2.1.3, 2.1.4, 2.1.5, 2.1.6, 2.2.0, 2.3.0, 2.3.1, 2.3.2, 3.0.0, 3.1.0, 3.1.1, 3.1.2, 3.1.3, 3.1.4, 3.2.0, 3.2.1, 3.2.2, 3.2.3) No matching distribution found for asgiref==3.2.7 (from -r requirements.txt (line 1))

Repro Steps:

  1. Go to Python Quick Start, complete steps 1 (Python select) and 2 (App ID registration)
  2. Return back to MS Graph developer portal, enter client secret value for quick start app
  3. Confirm "Registration Successful!", move on to "Step 3: Start coding"
  4. Click download button for "Download the REST-based code sample"
  5. Download and unzip the file (Windows platform)
  6. In WSL (Windows Subsystem for Linux) environment, Ubuntu shell within Windows Terminal, navigate to the extracted folder (msgraph-training-pythondjangoapp)
  7. Confirm python and python-pip are installed (Python 2.7.17, pip 9.0.1)
  8. Run pip install -r requirements.txt
  9. Receive error listed above
  10. Attempt in sudo, just to be sure
  11. Receive same error listed above

Unauthenticated user cannot access the site.

Thank you for provided tutorial, it is very useful.

I need to enhance the login-only-user permission for my site using the provided sample.
I have developed the following class for this purpose:

class LoginWithAccessTokenMixin:
    """
    Check if user authenticated with access token. If the user is not, redirect to login page.
    """
    login_url = "/"

    def dispatch(self, request, *args, **kwargs):
        """
        Extend behavior of parent class method.

        Try to receive session's access token. If user is authenticated and token exists, display view.
        If token doesnt' exist, function get_token raises IndexError and method redirects user to sign in page.
        """
        try:
            self.access_token = get_token(request)
            return super().dispatch(request, *args, **kwargs)
        except IndexError:
            return HttpResponseRedirect(self.login_url)

Now every view in project inherit from this class. From manual testing it looks fine and not authenticated user is redirected to login page of Microsoft.
Could you, please, advise if it is secure enough or some additional functionality should be implemented?
Thank you in advance.

gert_token - Refresh Token missing

On expiration the get_token function gets an error:

(invalid_request) AADSTS900144: The request body must contain the following parameter: 'refresh_token'.

Appears the token doesn't carry this field at all? @jasonjoh

MissingTokenError

I am getting the error (missing_token) Missing access token parameter. It is related to the file auth_helper specifically token = aad_auth.fetch_token(token_url, client_secret = settings['app_secret'], authorization_response=callback_url)

I couldn't find anything related to this on web

When running the completed project from here I find no issues. Any idea?

Getting Socket error

On the visual studio code terminal , i see below socket error, when the screen is on outlook Stay signed in?


[15/Sep/2020 21:49:05] "GET /signin HTTP/1.1" 302 0


Exception happened during processing of request from ('127.0.0.1', 61248)
Exception happened during processing of request from ('127.0.0.1', 61247)
Traceback (most recent call last):
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 720, in init
self.handle()
Traceback (most recent call last):
File "C:\Users\smednika\Envs\MSGproject\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle
self.handle_one_request()
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 650, in process_request_thread
self.finish_request(request, client_address)
File "C:\Users\smednika\Envs\MSGproject\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socket.py", line 669, in readinto
return self._sock.recv_into(b)
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 360, in finish_request
self.RequestHandlerClass(request, client_address, self)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socketserver.py", line 720, in init
self.handle()

File "C:\Users\smednika\Envs\MSGproject\lib\site-packages\django\core\servers\basehttp.py", line 172, in handle
self.handle_one_request()
File "C:\Users\smednika\Envs\MSGproject\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request
self.raw_requestline = self.rfile.readline(65537)
File "c:\users\smednika\appdata\local\programs\python\python38\lib\socket.py", line 669, in readinto
return self._sock.recv_into(b)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host

outlook

authority issue needs to be discussed in tutorial

as part of the tutorial depending on what authority you are using ( personal or consumer) you may need to change the yaml file to suit.. e.g if you are using a personal file you would need to use the consumers authority, prob worth calling out in the tutorial.
Screen Shot 2021-06-03 at 4 59 20 pm

Redirection to the incorrect locale

Describe the bug

The bug is in the hosted page at https://docs.microsoft.com/en-us/graph/tutorials/python
When I access the Python quick start from the tip, it redirects to the ru-ru localised page instead of en-us

To Reproduce

  1. Go to https://docs.microsoft.com/en-us/graph/tutorials/python
  2. Click on Python quick start
  3. It opens the Russian language site - https://developer.microsoft.com/ru-ru/graph/quick-start?platform=option-Python

Expected behavior

The expectation was that in step 3 above the redirection will happen to https://developer.microsoft.com/en-us/graph/quick-start?platform=option-Python respecting the localisation of the previous url

Desktop

  • OS: Windows 10
  • Browser Edge Chromium
  • Version 91.0.831.0

AADSTS50011

Have followed the tutorial but am receiving the AADSTS50011 error, i.e. : The reply url specified in the request does not match the reply urls configured for the application: 'xxxx'. It is very hard to debug this when I cannot find the "reply url specified in the request". The logs in the AAD admin center do record my failed attempts to log-in but they do not appear to contain the reply url that causes the error. How can I find what AAD receives?

My setup has Nginx, Gunicorn fronting Django running on OSX.

Thanks for any help.

Error while trying to read emails

{'error': {'code': 'ErrorAccessDenied', 'message': 'Access is denied. Check credentials and try again.', 'innerError': {'request-id': 'd6803fce-e258-4627-bc8d-f0ab25c84a94', 'date': '2020-01-09T06:05:28'}}}

I am getting above response when I add a method get_email_events(token) in graph_helper.py. please help.

method implementation in tutorial/graph_helper.py

def get_email_events(token):
graph_client = OAuth2Session(token=token)
print(str(graph_client)+" in email")
query_params = {
'$filter':"importance eq 'high'"
}

Send GET to /me/events

events = graph_client.get('{0}/me/events'.format(graph_url), params=query_params) # Return the JSON result

print(events.json())

return events.json()

Quotes Needed on YAML Values

When the app_secret, or any other config values, end with a colon you get this error when trying to generate the database:

C:\GraphPython\graph_tutorial>python manage.py migrate
yaml.scanner.ScannerError: mapping values are not allowed here
in "oauth_settings.yml", line 2, column 35

All values in the oauth_settings.yml file should have strings around them. This fixes the problem.

The term 'python' is not recognized

https://developer.microsoft.com/en-us/graph/quick-start?appID=9b019258-e2d4-4800-8d5d-6368482e027b&appName=My%20Python%20App&redirectUrl=http://localhost:8000/tutorial/callback&platform=option-Python

On running the code the following error is encountered:

python : The term 'python' is not recognized as the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1

  • python manage.py migrate
  •   + CategoryInfo          : ObjectNotFound: (python:String) [], CommandNotFoundException
      + FullyQualifiedErrorId : CommandNotFoundException
    
    
    

name 'get_token' is not defined

On 'Add Azure AD authentication' section, get_token should be added in the below line. At the moment, get_token is not included in that line which is why "name 'get_token' is not defined" error appears if we just follow and copy-paste the tutorial.

from tutorial.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token

Not pulling calendar events

Where did you get the code?

Describe the bug

I ran the GitHub version and the tutorial version. Was able to post a new event successfully, but couldn't output any calendar events.

I had the former version of the tutorial installed this morning and that did pull the calendar events.

To Reproduce

Steps to reproduce the behavior:

  1. Go to calendar
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

A clear and concise description of what you expected to happen.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: iOs
  • Browser safari
  • Version [e.g. 22]

Dependency versions

  • Authentication library (MSAL, etc.) version: as per tutorial
  • Graph library (Graph SDK, REST library, etc.) version: as per tutorial

Additional context

Add any other context about the problem here.
printed the events:

{'@odata.context': "https://graph.microsoft.com/v1.0/$metadata#users('---')/calendarView(subject,organizer,start,end)", 'value': []}

Authentication Problem - ValueError at /callback

Where did you get the code?

Describe the bug

I have tried the app yesterday and after the first exact failure, I could log myself in and see it in action.
I am using a private browser app, so there shouldn't be any cookies or cached stuff to tingle with the process.
When I try to login today (>10), I always get the following message:

ValueError at /callback

state missing from auth_code_flow

Request Method: GET
Request URL: http://localhost:8000/callback?code=0.AVwANZ13ITsdhUGVdm7g9A1fkIkaKWOWuZlLvnJqReF8NOdcAFs.AQABAAIAAAD--DLA3VO7QrddgJg7Wevrwn9GL6n419-3vKseQ21BDs0bg-z5Fzt-rAP96yR4TiJaWfhgkx4bClcw2DbN9bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxsYC-CoZeVSMY7Ewl_FKoyeehXffGqWnb3N_ci2M9OWEPjggNedDJwa88SoCq7c2NHXU9ZAkZzWhFyaedykWMenNY4WUBWQkv-LeNgu_IeEkNz3naAR-WckBHrDt2Px8aR0I6_ROa4EAB9fyq-UskuyANcXlHb5nLgOMLiRyS-I16yeHlT_y8fXnrzS09o44fqu1VNTVveQgKL7UUE2M7wP_BoRG0CPlKAGiJI3BnTz2g_mkTsk577KPxyUR5d4vo2EFQD-bJb6dEHD1xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx75Wir-ON0Dw6havPpfwjQM4Iuehy875GQI-0RfNVvpuc-imkUv6V-V22nfjtnnrhFeO3c7lSZ6q3_dH_MwGzxcBMXyUqGqsokCvLOLp8VseSjlTURHD0WPe9cPd02107N881WLBT_R-bsp03k2AzabuJUzvBukS9l7O-We09xL9uR5TQTLV0yhd8JQ6mhQxqtcNwfALRnD8xNQSlUDGVjgB06crktqbQbF1BiWJfJGsoOImTfB1HDBiWmVdjOPL5Jngs0-dOhNx038UNnGHKtr_TQED9HZLQ4-_2bBWyKqdbXzHst2Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxq_DroXJE4uNKNglrk8kogAA&state=xxxxxxxxxxxAkpxg&session_state=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Django Version: 3.2
Exception Type: ValueError
Exception Value:  state missing from auth_code_flow
Exception Location: C:\Users\xxx\Code\msgraph-training-pythondjangoapp\venv\lib\site-packages\msal\oauth2cli\oauth2.py, line 540, in obtain_token_by_auth_code_flow
Python Executable: C:\Users\xxx\Code\msgraph-training-pythondjangoapp\venv\Scripts\python.exe
Python Version: 3.9.9
Python Path: ['C:\Users\xxx\Code\msgraph-training-pythondjangoapp\graph_tutorial', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\xxx\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\xxx\Code\msgraph-training-pythondjangoapp\venv', 'C:\Users\xxx\Code\msgraph-training-pythondjangoapp\venv\lib\site-packages']
Server time: Tue, 30 Nov 2021 13:32:56 +0000

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'home page'
  2. Click on 'Login'
  3. Get forwarded to Microsoft Login
  4. Complete the login with Athenticator, SMS
  5. See the error.

Expected behavior

Getting redirected to localhost:8000/ as an authenticated user.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: Windows 10
  • Browser Chrome Version 96.0.4664.45

Dependency versions

  • Python 3.9.9
  • Authentication library (MSAL, etc.) version: msal==1.10.0
  • Django==3.2

Additional context

Any idea why this is happening?

PermissionsError: [Errno 13] on oauth_settings.yml with Apache

Everything runs fine for this example with the django development server

If you move to Apache as the webserver, you will hit a permissions error on the oauth_settings.yml file
that will generate lines in the Apache error log that look like this:

[Fri Nov 08 12:23:02.307540 2019] [wsgi:error] [pid 17268:tid 1340] [client ::1:61476] Internal Server Error: /\r
[Fri Nov 08 12:23:02.308537 2019] [wsgi:error] [pid 17268:tid 1340] [client ::1:61476] PermissionError: [Errno 13] Permission denied: 'C:/Users/your_user/yourpath/graph/oauth_settings.yml'\r

The yellow Django error page will also show some this permission error 13 information

This is happening because the oauth_settings.yml file from Microsoft has a Windows Information Protection policy applied to it (MAM policy), that apparently is triggered by the move to the Apache server. Policy is described by following the link below.

To resolve, navigate via File Explorer to the oauth_settings.yml file and right click on it. In the popup, you should see an entry on the popup that says "File Ownership", click on that and a little popout to the side saying "Personal" with an icon that looks like an unlocked padlock will appear. Click on this (which apparently unlocks the file for personal use), and the Permission error will be gone. See image below for more info

For more info on this MS policy: https://blogs.technet.microsoft.com/cbernier/2017/05/19/windows-information-protection-explained-windows-10-creators-update/

File Ownership

Home Page is Not rendering after Providing Credentials

Where did you get the code?

Followed the tutorial from Microsoft Graph tutorials

Describe the bug

I have followed the steps exactly provided in Graph tutorials, after clicking on Sign on Microsoft login Page is appearing, and i have provided microsoft credentials, then its not rendering the home page, giving Value error , State missing in Auth Code Flow

Environment:

Request Method: GET
Request URL: http://localhost:8000/callback?code=M.R3_BAY.9074896a-0d08-58f3-0241-510fa2fdad5e&state=tCOXIJfsDRejZLPk

Django Version: 3.1.5
Python Version: 3.9.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'tutorial']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']

Traceback (most recent call last):
File "D:\Django_Projects\Projects\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "D:\Django_Projects\Projects\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Django_Projects\Projects\graph_tutorial\tutorial\views.py", line 37, in callback
result = get_token_from_code(request)
File "D:\Django_Projects\Projects\graph_tutorial\tutorial\auth_helper.py", line 49, in get_token_from_code
result = auth_app.acquire_token_by_auth_code_flow(flow, request.GET)
File "D:\Django_Projects\Projects\venv\lib\site-packages\msal\application.py", line 513, in acquire_token_by_auth_code_flow
return self.client.obtain_token_by_auth_code_flow(
File "D:\Django_Projects\Projects\venv\lib\site-packages\msal\oauth2cli\oidc.py", line 185, in obtain_token_by_auth_code_flow
result = super(Client, self).obtain_token_by_auth_code_flow(
File "D:\Django_Projects\Projects\venv\lib\site-packages\msal\oauth2cli\oauth2.py", line 538, in obtain_token_by_auth_code_flow
raise ValueError("state missing from auth_code_flow")

Exception Type: ValueError at /callback
Exception Value: state missing from auth_code_flow

Please help here

Update documentation

Where did you get the code?

Followed the tutorial from Microsoft Graph tutorials

Describe the bug

There is a typo in the documentation that refers to a non-existent function, get_sign_in_url leading to unnecessary ImportError.

from tutorial.auth_helper import get_sign_in_url, get_token_from_code, store_user, remove_user_and_token, get_token

To Reproduce

Steps to reproduce the behavior:

  1. Go to 'Python tutorial main page'
  2. Click on 'Step 3: Add Azure AD authentication'
  3. Scroll down to 'Step 5 under Get user details'
  4. See typo

Expected behavior

from tutorial.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token

Screenshots

graph_python_typo

Question about console graph api authentication

I am making one console based application where i can do the same thing but without running django server so i tied the auth_helper.py and from it i generated a perfect sign_in_url along state[changed client_id]. So need suggestion a bit on this code.

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=code&client_id=b0c3374c-c5e3-4ac0-&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&scope=openid+profile+offline_access+user. read+calendars.read+Calendars.ReadWrite+calendars.readwrite&state=Rr2LAjUBGr4ScoJ9qccfhIsqk6rkwD

I hope it's correct at first point

and then i requested it as a input enter the callback url after the sign in and got that as well so no on to the second function which is get_token_from_code

callback_url = input("Enter the callback url from browser after logging in, copy the above link to login.")

def get_token_from_code(callback_url, expected_state):
    add_auth = OAuth2Session(settings['app_id'], state=expected_state, scope=settings['scopes'],
                             redirect_uri=settings['redirect'])
    token = add_auth.fetch_token(token_url, client_secret=settings['app_secret'], authorization_response=callback_url)

    return token

get_token_from_code()
  • Now here, first is it right callback_url which is expected here in this function ?

  • and what i am supposed to pass in expected_state to get the final access_token with auth_token

  • what value is supposed to be passed in token_url variable.

is user_athenticated not being set to true on login

Thank you for taking an interest in Microsoft Graph development! Please feel free to ask a question here, but keep in mind the following:

  • This is not an official Microsoft support channel, and our ability to respond to questions here is limited. Questions about Graph, or questions about adding a new feature to the sample, will be answered on a best-effort basis.
  • Questions should be asked on Stack Overflow.
  • Issues with Microsoft Graph itself should be handled through support.

POST Send Email Python Django

I am pretty new in python and ms graph and i am trying to create a page to send email through django, but I was unsuccessful.
return http 403.

#From outlookservices.py
def send_email(access_token):
send_email_url = graph_endpoint.format('/me/sendMail') # /me/messages/{id}/send
payload = {'Message': {'Subject': subject,
'Body': {'ContentType': content_type, 'Content': body},
'ToRecipients': recipient_list,
'Attachments': attached_files},
'SaveToSentItems': 'true'}

r = make_api_call('POST', send_email_url, access_token, payload)
if (r.status_code == requests.codes.ok):
print("OK")
return r.json()
else:
print(r)
return "{0}: {1}".format(r.status_code, r.text)

#views.py
def sendemail(request):
access_token = get_access_token(request, request.build_absolute_uri(reverse('app:gettoken')))
if not access_token:
print("not token")
return HttpResponseRedirect(reverse('app:home'))
else:
print("token")
messages = send_email(access_token)
context = { 'messages': messages }
return render(request, 'pages/sendemail.html', context)

could you help me with anyidea?
on the web e on the official documentation i just can find GET methods examples.

thanks a lot
Sorry if I am asking in a wrong place.

KeyError at /tutorial/calendar 'value'

Hi. Thank you very much for your work.

In the use of the program, I encountered a problem, I have successfully logged in, but when I get calendar information, I received such an error.

Internal Server Error: /tutorial/calendar Traceback (most recent call last): File "D:\python\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\python\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\python\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\python\django项目\Github网站\graph_tutorial\tutorial\views.py", line 66, in calendar for event in events['value']: KeyError: 'value'

I printed token and got the following
{'token_type': 'Bearer', 'scope': ['Calendars.Read', 'openid', 'profile', 'User.Read', 'email'], 'expires_in': 3599, '

image
I found that I should not have permissions, so I opened it in the application settings, but when I logged in from the new time, he still did not get these permissions; so where should I open it? Thank you

POST requests?

I have been able to successfully run the tutorial code with GET requests. Now I wish to make POST requests with a graph_client.post(https://graph.microsoft.com/v1.0/users, data={'userPrincipalName': '[email protected]', etc... }) type of construction. Unfortunately this generates a HTTP 400 message of the form 'code': 'BadRequest', 'message': 'Entity only allows writes with a JSON Content-Type header.'. Will the tutorial constructs work with POST requests?
Thanks!
David

=====
Update.
I was able to resolve my issue by using post requests that include an explicit Content-Type header, like so:

graph_client.post(cmd[1], data=json.dumps(ext_cmd[1]),
headers={"Content-Type": "application/json"})

I now consider this issue to be closed.
Thanks.

Question about Tutorial code

Hello team,

I followed the tutorial:

https://github.com/microsoftgraph/msgraph-training-pythondjangoapp

https://docs.microsoft.com/en-us/graph/tutorials/python

It is working. However, I would like to know how to get token for multiple scopes of difference resources:

For example, the tutorial guides to call with Microsoft Graph, but I also need to call Azure Management Services api within same django web app.

I reviewed some other codes and see there is a way with acquire_token_silent but I do not know how to implement it in this Tutorial and how to use this new token along with the old token of aother resource.

Hope to have your feedback soon.

David.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.