@@ -527,174 +527,34 @@ with signed and encrypted user data using `itsdangerous.Serializer`.
527527
528528### Basic Cookie authentication setup
529529
530- The following example shows how to configure Cookie authentication :
530+ The following example shows how to use the built-in ` CookieAuthentication ` class :
531531
532532``` python
533- from blacksheep import Application, get, json
534- from blacksheep.server.authentication.cookie import CookieAuthentication
535- from blacksheep.server.authorization import auth
536-
537- app = Application()
538-
539- # Configure cookie authentication
540- app.use_authentication().add(
541- CookieAuthentication(
542- cookie_name = " user_session" , # Default: "identity"
543- secret_keys = [" your-secret-key" ], # Keys for signing/encryption
544- auth_scheme = " CookieAuth" # Custom scheme name
545- )
546- )
547-
548- app.use_authorization()
549-
550-
551- @auth ()
552- @get (" /profile" )
553- async def get_profile (request ):
554- return {
555- " message" : " User profile" ,
556- " user" : request.user.claims
557- }
558-
559-
560- @get (" /login" )
561- async def login (request ):
562- """ Example login endpoint that sets authentication cookie"""
563- response = json({" message" : " Login successful" })
564-
565- # Get the cookie authentication handler
566- cookie_auth = app.services.resolve(CookieAuthentication)
567-
568- # Set user data in cookie (typically done after validating credentials)
569- user_data = {
570- " sub" : " user123" ,
571- " name" : " John Doe" ,
572- " roles" : [" user" ],
573- " exp" : 1234567890 # Optional expiration timestamp
574- }
575-
576- cookie_auth.set_cookie(user_data, response, secure = True )
577- return response
578-
579-
580- @get (" /logout" )
581- async def logout (request ):
582- """ Example logout endpoint that removes authentication cookie"""
583- response = json({" message" : " Logged out" })
584-
585- # Get the cookie authentication handler
586- cookie_auth = app.services.resolve(CookieAuthentication)
587-
588- # Remove the authentication cookie
589- cookie_auth.unset_cookie(response)
590- return response
591- ```
533+ import secrets
534+ from datetime import datetime, timedelta, UTC
592535
593- ### Advanced Cookie configuration
594-
595- You can customize the cookie authentication with additional options:
596-
597- ``` python
598- from blacksheep import Application
599- from blacksheep.server.authentication.cookie import CookieAuthentication
600- from itsdangerous import JSONWebSignatureSerializer
601-
602- app = Application()
603-
604- # Advanced configuration with custom serializer
605- custom_serializer = JSONWebSignatureSerializer(" your-secret-key" )
606-
607- app.use_authentication().add(
608- CookieAuthentication(
609- cookie_name = " app_session" ,
610- secret_keys = [" primary-key" , " backup-key" ], # Key rotation support
611- serializer = custom_serializer, # Custom serializer
612- auth_scheme = " CustomCookieAuth"
613- )
614- )
615- ```
616-
617- ### Working with cookie data
618-
619- The cookie authentication handler provides methods to manage authentication cookies:
620-
621- ``` python
622- from blacksheep import Application, get, post, json
536+ from blacksheep import Application, get, json, post
623537from blacksheep.server.authentication.cookie import CookieAuthentication
624538
625539app = Application()
626540
541+ # Secure cookie configuration
627542cookie_auth = CookieAuthentication(
628- cookie_name = " session" ,
629- secret_keys = [" your-secret-key" ]
543+ cookie_name = " secure_session" ,
544+ secret_keys = [
545+ secrets.token_urlsafe(32 ),
546+ secrets.token_urlsafe(32 ),
547+ ],
630548)
631-
632549app.use_authentication().add(cookie_auth)
633550
634551
635- @post (" /api/signin" )
636- async def signin (request ):
637- """ Sign in endpoint that validates credentials and sets cookie"""
638- # TODO : Validate user credentials from request body
639-
640- response = json({" success" : True })
641-
642- # Set authentication cookie with user claims
643- user_claims = {
644- " sub" : " user123" ,
645- " email" : " user@example.com" ,
646- " roles" : [" user" , " admin" ],
647- " department" : " IT"
648- }
649-
650- cookie_auth.set_cookie(user_claims, response, secure = True )
651- return response
652-
653-
654- @post (" /api/signout" )
655- async def signout (request ):
656- """ Sign out endpoint that removes the authentication cookie"""
657- response = json({" message" : " Signed out successfully" })
658- cookie_auth.unset_cookie(response)
659- return response
660-
661-
662- @get (" /api/user" )
663- async def get_current_user (request ):
664- """ Get current user info from cookie authentication"""
665- if request.user and request.user.is_authenticated():
666- return json({
667- " authenticated" : True ,
668- " claims" : request.user.claims
669- })
670- else :
671- return json({" authenticated" : False })
672- ```
673-
674- ### Cookie security considerations
675-
676- When using cookie authentication, consider these security practices:
677-
678- ``` python
679- from blacksheep import Application
680- from blacksheep.server.authentication.cookie import CookieAuthentication
681- from datetime import datetime, timedelta
682-
683- app = Application()
684-
685- # Secure cookie configuration
686- app.use_authentication().add(
687- CookieAuthentication(
688- cookie_name = " secure_session" ,
689- secret_keys = [
690- " primary-secret-key-256-bits-long" ,
691- " backup-secret-key-for-rotation"
692- ]
693- )
694- )
552+ @get (" /" )
553+ async def home (request ) -> dict :
554+ return request.user.claims
695555
696556
697- @app.route (" /login" , methods = [ " POST " ] )
557+ @post (" /login" )
698558async def secure_login (request ):
699559 # TODO : Validate credentials
700560
@@ -704,18 +564,32 @@ async def secure_login(request):
704564 user_data = {
705565 " sub" : " user123" ,
706566 " name" : " John Doe" ,
707- " exp" : int ((datetime.utcnow( ) + timedelta(hours = 24 )).timestamp())
567+ " exp" : int ((datetime.now( UTC ) + timedelta(hours = 24 )).timestamp()),
708568 }
709569
710- cookie_auth = app.services.resolve(CookieAuthentication)
711570 cookie_auth.set_cookie(
712571 user_data,
713572 response,
714- secure = True # Always use secure=True in production with HTTPS
573+ secure = True , # Always use secure=True in production with HTTPS
715574 )
716575 return response
576+
577+
578+ @get (" /logout" )
579+ async def logout (request ):
580+ """ Example logout endpoint that removes authentication cookie"""
581+ response = json({" message" : " Logged out" })
582+
583+ # Remove the authentication cookie
584+ cookie_auth.unset_cookie(response)
585+ return response
717586```
718587
588+ ** Summary:**
589+ - ` set_cookie ` is used to securely set an authentication cookie containing user claims and expiration, typically after a successful login.
590+ - ` unset_cookie ` removes the authentication cookie, logging the user out.
591+ - ` request.user.claims ` allows you to access the authenticated user's claims in request handlers, such as user ID, name, or roles.
592+
719593/// admonition | Security recommendations
720594 type: warning
721595
0 commit comments