1 year ago

#349695

test-img

Yonatan

understanding Starlette authentication

I'm trying to build a login page for a web application.

As documented here: https://www.starlette.io/authentication/ I have the following:

class BasicAuthBackend(AuthenticationBackend):
    async def authenticate(self, conn):
        if "Authorization" not in conn.headers:
            return
        # auth = ...
        # further decoding and validating. assuming credentials are verified:
        return AuthCredentials(["authenticated"]), SimpleUser("user")

I have added middleware as follows:

middleware = [
    Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())]

my endpoints:

@app.route('/', methods=['GET'])
async def homepage(request):
    if request.user.is_authenticated:
        return templates.TemplateResponse('index.html', {'request': request})
    else:
        return RedirectResponse(url=app.url_path_for('login'))

@app.route('/login', methods=['GET'])
async def login(request):
    response = {'request': request}
    return templates.TemplateResponse('login.html', response)

in login.html I have a form, and I added:

$('#formSubmit').on('click',function(){
username = document.getElementById("userName").value;
password = document.getElementById("password").value;
$.ajax({
      url: '{{ url_for("homepage") }}',
      type: 'GET',
      contentType: 'application/json',
      headers: {
                "Authorization": "Basic " + btoa(`"${username}:${password}"`)
             },
      async: false
        })});

I run the app and get redirected to the login page, as expected:

"GET / HTTP/1.1" 307 Temporary Redirect
"GET /login HTTP/1.1" 200 OK

(Here I end up on http://127.0.0.1:8000/login)

I then fill some (valid) credentials on the form, and when I submit, I expect to have a single get request to the home page like:

"GET / HTTP/1.1" 200 OK

but for some frustrating reason I have two GET requests:

"GET / HTTP/1.1" 200 OK
"GET /login HTTP/1.1" 200 OK

and I end up on http://127.0.0.1:8000/login? (note the "?" in the end)

Thanks in advance.

Edit

the reason for having two GET requests is because there was a form submit in addition to the ajax call, so now I changed my js:

function submitButtonClick(event) {
    event.preventDefault();
    username = document.getElementById("userName").value;
    password = document.getElementById("password").value;
    $.ajax({
      url: '{{ url_for("homepage") }}',
      type: 'GET',
      contentType: 'application/json',
      headers: {
                "Authorization": "Basic " + btoa(`"${username}:${password}"`)
             },
      success: # how to display the template response??
        async: false
        });
     } 

javascript

python

authentication

starlette

0 Answers

Your Answer

Accepted video resources