1

I have a page that is rendered only for logged in users that have a partcular role, something like this

@app.route("/")
@login_required
@roles_required("admin")
def admin_view():
    return render_template("admin_page.html")

and I want a button inside this page that makes a POST request to a particular endpoint and I want this endpoint to be protected to prevent requests from unauthorized users. How can I do this?

Since I also have flask-jwt-extended setup in my project (because it also serves as an API server for a mobile app) I protected the endpoint by requiring a jwt token

@app.route("/activate", methods=["POST"])
@jwt_required
def activate():
    # Do something

Each time the page is rendered, I generate a token and place it inside the html so that I can use it in javascript to make the request.
I think this is quite a brutal and sub-optimal way of doing this.

Is there any better way of protecting an endpoint with flask-security?

Elia Perantoni
  • 581
  • 1
  • 6
  • 19

1 Answers1

1

Got it, it's as simple as @login_required actually.
I didn't know ajax requests carried cookies as well, good to know!
I'll still need a separate endpoint if I ever need to make that request on the mobile app to use the token or make some kind of self-made decorator that accepts either auth method

@app.route("/activate", methods=["POST"])
@login_required
def activate():
    # Do something
Elia Perantoni
  • 581
  • 1
  • 6
  • 19