1

I am following this tutorial on how to generate a code and access token using Microsoft's identity platform. I am able to get the code by hitting the /authorize endpoint in a browser from a redirect. Then using thunderclient in VSCode and I am able to get an access token and use that access token to call microsoft graph and get my information.

I am using FastAPI for the backend of my webapp and I am trying to set up API endpoints to retrieve the code and access tokens through python's Requests library. However, when I hit the /authorize endpoint, within my swagger docs, it does not redirect to the microsoft login screen like it would if I did it within a browser. Here's what I am trying to do:

def get_code():
    url = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize'

    params = {'client_id': 'my-client-id', 'response_type': 'code',
            'redirect_uri': 'http://localhost:4200', 'response_mode': 'query',
            'scope': 'offline_access%20user.read%20mail.read', 'state': '12345'
    }

    resp = requests.get(url=url, params=params)
    return resp.text
@router.get("/code")
def get_user_code():
    user_code = login_helper.get_code()
    return user_code

The output seems like it returns the Microsoft login screen and tries to redirect but does not.

<!-- Copyright (C) Microsoft Corporation. All rights reserved. -->
<!DOCTYPE html>
<html dir="ltr" class="" lang="en">
  <head>
    <title>Sign in to your account</title>

Is it possible to be redirected when hitting the endpoint in swagger? If not, What would be the best way to get the code within FastAPI?

Any help would be appreciated.

Chris
  • 18,724
  • 6
  • 46
  • 80
ldisalvo
  • 11
  • 2
  • You can look into [RedirectResponse](https://fastapi.tiangolo.com/advanced/custom-response/?h=redi#redirectresponse) – Irfanuddin Sep 06 '22 at 19:08
  • @Irfanuddin I've tried using redirectresponse and I get a CORS error that I have not been able to resolve – ldisalvo Sep 06 '22 at 19:23
  • @Chris Do you know of a way to get the code from the redirect response? After I hit the endpoint in a browser the code can be seen in the url. So I'm unsure how to get the code within a function – ldisalvo Sep 07 '22 at 12:55
  • Does this answer your question? [How to send RedirectResponse from a POST to a GET route in FastAPI?](https://stackoverflow.com/questions/73076517/how-to-send-redirectresponse-from-a-post-to-a-get-route-in-fastapi) – Chris Nov 06 '22 at 11:20
  • Does this answer your question? [FastAPI's RedirectResponse doesn't work as expected in Swagger UI](https://stackoverflow.com/questions/73607320/fastapis-redirectresponse-doesnt-work-as-expected-in-swagger-ui) – Chris Dec 27 '22 at 17:39
  • I was able to set up a listener to pulled in the code from the url on my front end. A bit of a workaround so I didn't have to redirect in the backend. @Chris – ldisalvo Dec 28 '22 at 15:58

0 Answers0