jczic / MicroWebSrv

A micro HTTP Web server that supports WebSockets, html/python language templating and routing handlers, for MicroPython (used on Pycom modules & ESP32)
https://github.com/jczic/MicroWebSrv
MIT License
640 stars 115 forks source link

Basic Authentication Implementation #33

Closed lmsoria closed 6 years ago

lmsoria commented 6 years ago

Hi, I'm trying to implement a Basic Authentication method when I access a web site allocated on a LoPy4.

I've successfully managed to do this (in a quite naive way) inside a route handler:

@MicroWebSrv.route('/auth')
def _httpHandlerAuth(httpClient, httpResponse) :
    responseCode = 401

    requestHeader = httpClient.GetRequestHeaders()
    print(requestHeader)

    try:
        rta = validateAuthentication(requestHeader['Authorization'])
        if(rta == True):
            responseCode = 200
    except KeyError:
        pass

    print("response Code: ", responseCode)
    if(responseCode == 200):
        myHeader = dict()
        myHeader['Access-Control-Allow-Origin'] = '*'
        myHeader['Access-Control-Allow-Methods'] = 'GET, POST'
        httpResponse.WriteResponseOk(headers         = myHeader,
                                     contentType     = "text/plain",
                                     contentCharset = "UTF-8",
                                     content         = 'Login OK :)' )
    else:
        myHeader = dict()
        myHeader['Access-Control-Allow-Origin'] = '*'
        myHeader['Access-Control-Allow-Methods'] = 'GET, POST'
        myHeader['Authorization'] = 'Basic'
        myHeader['WWW-Authenticate'] = 'Basic realm="401"'
        httpResponse.WriteResponse( code = responseCode,
                                    headers      = myHeader,
                                    contentType  = "text/plain",
                                    contentCharset = "UTF-8",
                                    content          = None)

def validateAuthentication(request):
    # Mock User and Password
    user = "admin"
    pwd = "1234"

    ret = False

    request_enc = request.split(" ")[1]
    request_dec = str( base64.b64decode(request_enc) )
    aux = request_dec.split("'")
    aux = aux[1].split(":")
    print("aux: ", aux)

    request_user = aux[0]
    request_pass = aux[1]
    print('User: ', request_user)
    print('Pass: ', request_pass)

    if(request_user == user and request_pass == pwd):
        print("OK!!!")
        ret = True
    return ret

I would like to implement something similar to this but before accessing the index.html file allocated inside the /www directory. If I write the same code as before, but using @MicroWebSrv.route('/') then I cannot access the index.html file (as expected).

Is there a way to implement this authentication method? Thanks in advance!

jczic commented 6 years ago

Hello, can you try with @MicroWebSrv.route('') ?

Le ven. 15 juin 2018 à 15:15, Leandro Soria notifications@github.com a écrit :

Hi, I'm trying to implement a Basic Authentication method when I access a web site allocated on a LoPy4.

I've successfully managed to do this (in a quite naive way) inside a route handler:

@MicroWebSrv.route('/auth') def _httpHandlerAuth(httpClient, httpResponse) : responseCode = 401

requestHeader = httpClient.GetRequestHeaders()
print(requestHeader)

try:
    rta = validateAuthentication(requestHeader['Authorization'])
    if(rta == True):
        responseCode = 200
except KeyError:
    pass

print("response Code: ", responseCode)
if(responseCode == 200):
    myHeader = dict()
    myHeader['Access-Control-Allow-Origin'] = '*'
    myHeader['Access-Control-Allow-Methods'] = 'GET, POST'
    httpResponse.WriteResponseOk(headers       = myHeader,
                                 contentType   = "text/plain",
                                 contentCharset = "UTF-8",
                                 content       = 'Login OK :)' )
else:
    myHeader = dict()
    myHeader['Access-Control-Allow-Origin'] = '*'
    myHeader['Access-Control-Allow-Methods'] = 'GET, POST'
    myHeader['Authorization'] = 'Basic'
    myHeader['WWW-Authenticate'] = 'Basic realm="401"'
    httpResponse.WriteResponse( code = responseCode,
                                headers        = myHeader,
                                contentType    = "text/plain",
                                contentCharset = "UTF-8",
                                content        = None)

def validateAuthentication(request):

Mock User and Password

user = "admin"
pwd = "1234"

ret = False

request_enc = request.split(" ")[1]
request_dec = str( base64.b64decode(request_enc) )
aux = request_dec.split("'")
aux = aux[1].split(":")
print("aux: ", aux)

request_user = aux[0]
request_pass = aux[1]
print('User: ', request_user)
print('Pass: ', request_pass)

if(request_user == user and request_pass == pwd):
    print("OK!!!")
    ret = True
return ret

I would like to implement something similar to this but before accessing the index.html file allocated inside the /www directory. If I write the same code as before, but using @MicroWebSrv.route('/') then I cannot access the index.html file (as expected).

Is there a way to implement this authentication method? Thanks in advance!

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/jczic/MicroWebSrv/issues/33, or mute the thread https://github.com/notifications/unsubscribe-auth/AAegLMpTZLBFz9Qkk3S_-nxAwgMzyi8sks5t87NggaJpZM4Upi1L .

--

Sincèrement,

lmsoria commented 6 years ago

Hi @jczic, I forgot to mention that I've tried your proposal, and the results remains the same. It shows me the authentication dialog, and then a black page with "Login OK :)" message.

jczic commented 6 years ago

If your handler function is triggered, the server doesn't return a page. May be try to delete the real html index page (the file) and respond on the fly ?

Le lun. 18 juin 2018 à 13:39, Leandro Soria notifications@github.com a écrit :

Hi @jczic https://github.com/jczic, I forgot to mention that I've tried your proposal, and the results remains the same. It shows me the authentication dialog, and then a black page with "Login OK :)" message.

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/jczic/MicroWebSrv/issues/33#issuecomment-398026246, or mute the thread https://github.com/notifications/unsubscribe-auth/AAegLEhUp7jdZPl7GcDfZ8kyVr1Ic_LWks5t95F6gaJpZM4Upi1L .

--

Sincèrement,

lmsoria commented 6 years ago

I've managed to show the index page in two different ways.

The first one (not so aesthetic, at least for me) using httpResponse.WriteResponseRedirect('/index.html') if the validation is OK. Is simple but in my case shows then on the navigator device_IP/index.html#/ and I particularly don't like how it looks.

The second one following your proposal:

f = open('/flash/www/index.html', 'r')
content= f.readall()
httpResponse.WriteResponseOk(headers = myHeader, contentType = "text/html", contentCharset = UTF-8", content = content)

Both ways worked fine, but I prefer the second one. Thank you for the suggestions!

jczic commented 6 years ago

Yes, the second solution is better :) You can also use .pyhtml files to code micropython in yours webpages directly :)

Le lun. 18 juin 2018 à 19:01, Leandro Soria notifications@github.com a écrit :

I've managed to show the index page in two different ways.

The first one (not so aesthetic, at least for me) using httpResponse.WriteResponseRedirect('/index.html') if the validation is OK. Is simple but in my case shows then on the navigator device_IP/index.html#/ and I particularly don't like how it looks.

The second one following your proposal:

f = open('/flash/www/index.html', 'r') content= f.readall() httpResponse.WriteResponseOk(headers = myHeader, contentType = "text/html", contentCharset = UTF-8", content = content)

Both ways worked fine, but I prefer the second one. Thank you for the suggestions!

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/jczic/MicroWebSrv/issues/33#issuecomment-398124532, or mute the thread https://github.com/notifications/unsubscribe-auth/AAegLDCWzqz7pXC-eS66CyIU5ZKnJrrCks5t99zygaJpZM4Upi1L .

--

Sincèrement,

jczic commented 4 years ago

Hello,

I released a fully new version (v2.0) of my web server here : github.com/jczic/MicroWebSrv2. Open source MIT, fully asynchronous, more robust, more fast and more efficient! It is delivered with a good documentation.

Thank you for your support and feedback. ☺️

Jean-Christophe Bos

Le lun. 18 juin 2018 à 19:15, Jean-Christophe Bos jczic.bos@gmail.com a écrit :

Yes, the second solution is better :) You can also use .pyhtml files to code micropython in yours webpages directly :)

Le lun. 18 juin 2018 à 19:01, Leandro Soria notifications@github.com a écrit :

I've managed to show the index page in two different ways.

The first one (not so aesthetic, at least for me) using httpResponse.WriteResponseRedirect('/index.html') if the validation is OK. Is simple but in my case shows then on the navigator device_IP/index.html#/ and I particularly don't like how it looks.

The second one following your proposal:

f = open('/flash/www/index.html', 'r') content= f.readall() httpResponse.WriteResponseOk(headers = myHeader, contentType = "text/html", contentCharset = UTF-8", content = content)

Both ways worked fine, but I prefer the second one. Thank you for the suggestions!

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/jczic/MicroWebSrv/issues/33#issuecomment-398124532, or mute the thread https://github.com/notifications/unsubscribe-auth/AAegLDCWzqz7pXC-eS66CyIU5ZKnJrrCks5t99zygaJpZM4Upi1L .

--

Sincèrement,

--

Sincèrement,