Azure-Samples / ms-identity-python-flask-webapp-call-graph

Python Flask web application that leverages MSAL Python to get an access token to call MS Graph API
MIT License
17 stars 5 forks source link

Add example for automatic sign-in redirect #2

Closed tdamsma closed 3 years ago

tdamsma commented 4 years ago

This issue is for a: (mark with an x)

- [ ] bug report -> please search issues before submitting
- [x] feature request
- [ ] documentation issue or request
- [ ] regression (a behavior that used to work and stopped in a new release)

The current implementation of the flask app redirects users to a 401.html page if they are not redirected. I would like to see an example where you are just redirected to the sign in process and then back to the page you intended to visit.

Next to a better experience in general, the reason I want this is that this would enable excel PowerQuery Web.Contents() queries to use Organizational authentication. This would be really helpful for me.

I sort of got it to work by changing the error handler:

    app.register_error_handler(
        NotAuthenticatedError,
        lambda err: (redirect(url_for("auth.sign_in")), 302),
    )

However this doesn't pass a redirect url to my original request, so after sign in I am sent to /sign_in_status even though I ogirinally requested /call_ms_graph.

idg-sam commented 3 years ago

Great suggestion! Maybe it is a property or param we can integrate into the state param on the oauth /authorize call?

idg-sam commented 3 years ago

Hi @tdamsma , I've updated our common code libraries to handle a post-sign-in redirect. I've also updated the sample to have your requested feature in a commented-out section. Please let me know if it works for you!

  1. download latest version
  2. comment line 39, and uncomment line 41
  3. run the app
    # tell flask to render the 401 template on not-authenticated error. it is not strictly required:
    app.register_error_handler(NotAuthenticatedError, lambda err: (render_template('auth/401.html'), err.code))
    # comment out the previous line and uncomment the following line in order to use (experimental) <redirect to page after login>
    # app.register_error_handler(NotAuthenticatedError, lambda err: (redirect(url_for('auth.sign_in', post_sign_in_url=request.url_rule))))
    # other exceptions - uncomment to get details printed to screen:
    # app.register_error_handler(Exception, lambda err: (f"Error {err.code}: {err.description}"))