简体   繁体   中英

How can I redirect to a protected URL after login in Flask?

I am developing a web project with microservices. In the backend, I have a Login service which is responsible for checking the user credentials and returning a valid JWT. I have another service called Views which is responsible for serving the UI and sending requests to other services. Every request coming from the client first visits Views service and then the requests are delivered to proper services.

The code for sending ajax request to "/login" route in the Views service:

function login(){
   $('#login-form').submit(function(){
      $.ajax({
          url: $('#login-form').attr('action'),
          type: 'POST',
          data : $('#login-form').serialize(),
          success: function(res, status, xhr){
             window.localStorage.setItem("x-access-token", xhr.getResponseHeader("x-access-token"));
             $.ajax({
                url: "/user/profile",
                type: "GET",
                headers: {
                  "x-access-token": window.localStorage.getItem("x-access-token")
                },
                success: function () {
                   window.location.replace("/user/profile")
                },
                error: function (response) {
                   alert("Error in GET: " + response)
                }
              });
          }, error: function (response) {
               alert(response)
          }
       })
    });
}

Code that delivers the request to Login service:

@views_blueprint.route("/login", methods=["POST"])
def user_login():
    email = request.form["email"]
    password = request.form["password"]

    r = requests.post("http://login:5000/login", json={"data": {"email": email, "password": password}})

    try:
        login_resp = r.json()
        if login_resp["status"] == 201:
            @after_this_request
            def send_token(response):
                response.headers["x-access-token"] = login_resp["token"]
                return response
            return json.dumps(login_resp)
        else:
            return render_template("/error/error.html", error_code=login_resp["status"], error_message=login_resp["message"])
    except Exception as e:
        return render_template("/error/error.html", error_code=500, error_message=f"Error occurred. {e}")

I can successfully send login request and get token back and store it in the localStorage. Issue I am having is, after logging in I need to redirect the user to a protected route and I need to add the JWT to the request headers. I tried to achieve this with an ajax GET request in the function login() . However, the GET request is never sent instead Flask renders the JSON object returned in the user_login() function.

How can I overcome this issue? If what I am doing is the wrong way, could anyone point me in the right direction?


I have just deal with JWT myself, so I saw you and I just wanted to give you a tip, I hope it will help you.
Your problem, if I've read that correctly, is that after a successful login you want to forward the user and valid token to the actual page in your app that is marked with jwt_required?
I always do it like this:
 # we are now in the login func and data is valid: access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) # now lets make a response object with a redirect: resp_obj = make_response(redirect(url_for('func_with_jwt_required'), 302)) # so now only the response object needs the token´s and you can return it set_access_cookies(resp_obj, access_token) set_refresh_cookies(resp_obj, refresh_token) return resp_obj

Please write to me if it helped you.
If not, please explain to me what I did not understand correctly about your method (because my method works on my applications without any problems), then I'll take a closer look at your problem and help you with your approach.

Nice day

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM