# FastAPI Session

***

**1. Simple Session Authentication**

```python
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET")

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**2. Session with Timeout**

```python
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", max_age=600)

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**3. Session with Persistent Storage**

```python
import os
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, SQLiteSession

app = FastAPI()
app.add_middleware(SQLiteSession, secret_key="SECRET", database=os.getenv("SQLITE_DATABASE"))

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**4. Session with Mongo Storage**

```python
import os
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, MongoSession

app = FastAPI()
app.add_middleware(MongoSession, secret_key="SECRET", uri=os.getenv("MONGO_URI"))

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**5. Session with Redis Storage**

```python
import os
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, RedisSession

app = FastAPI()
app.add_middleware(RedisSession, secret_key="SECRET", host=os.getenv("REDIS_HOST"), port=os.getenv("REDIS_PORT"))

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**6. Session with In-Memory Storage**

```python
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, InMemorySession

app = FastAPI()
app.add_middleware(InMemorySession, secret_key="SECRET")

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"]}
```

**7. Session with Custom Serializer**

```python
import os
from enum import Enum
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, BaseSerializer, Session

class UserRole(Enum):
    ADMIN = "admin"
    USER = "user"

class CustomSerializer(BaseSerializer):
    def loads(self, data: bytes) -> Session:
        return Session(username=data.decode("utf-8"), role=UserRole.USER)

    def dumps(self, session: Session) -> bytes:
        return session.username.encode("utf-8")

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", serializer=CustomSerializer())

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["username"] = "John"
    return RedirectResponse("/")

@app.get("/")
async def home(request: Request):
    session = await request.session()
    if "username" not in session:
        raise HTTPException(401)
    return {"username": session["username"], "role": session.role.value}
```

**8. Session with CSRF Protection**

```python
from fastapi import FastAPI, Request, HTTPException, Form
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", csrf_protection=True)

@app.get("/login")
async def login(request: Request):
    csrf_token = request.cookies.get("csrf_token")
    return {"csrf_token": csrf_token}

@app.post("/login")
async def login_post(request: Request, csrf_token: str = Form(...)):
    session = await request.session()
    if not session.is_token_valid(csrf_token):
        raise HTTPException(403)
    session["username"] = "John"
    return RedirectResponse("/")
```

**9. Session with Flash Messages**

```python
from fastapi import FastAPI, Request, HTTPException, Form
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", flash=True)

@app.get("/login")
async def login(request: Request):
    return {"flash_messages": request.session.get_flash_messages()}

@app.post("/login")
async def login_post(request: Request, username: str = Form(...)):
    session = await request.session()
    session["username"] = username
    session.add_flash_message("Welcome, {}!".format(username))
    return RedirectResponse("/")
```

**10. Session with Rate Limiting**

```python
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", rate_limit=10)

@app.get("/login")
async def login(request: Request):
    session = await request.session()
    session["login_count"] = session.get("login_count", 0) + 1
    if session["login_count"] > 10:
        raise HTTPException(403)
    return RedirectResponse("/")
```

**11. Session with JWT Authentication**

```python
import os
from fastapi import FastAPI, Request, HTTPException, Form
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, JWT_AUTH, Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", auth=JWT_AUTH)

@app.post("/login")
async def login(request: Request, username: str = Form(...)):
    session = await request.session()
    session["username"] = username
    token = session.get_jwt_token()
    return {"token": token}

@app.get("/logout")
async def logout(request: Request):
    session = await request.session()
    session.invalidate_jwt_token()
    return RedirectResponse("/")
```

**12. Session with OAuth2 Authentication**

```python
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, OAuth2Session

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", auth=OAuth2Session(client_id=os.getenv("CLIENT_ID"), client_secret=os.getenv("CLIENT_SECRET"), scope="email"))

@app.get("/login")
async def login(request: Request):
    redirect_uri = request.url_for("oauth2_callback")
    return RedirectResponse(request.session.get_oauth2_authorization_url(redirect_uri))

@app.get("/callback")
async def callback(request: Request):
    code = request.query_params.get("code")
    session = await request.session()
    access_token = session.get_oauth2_access_token(code)
    user_info = session.get_oauth2_user_info(access_token)
    return {"user_info": user_info}
```

**13. Session with Social Authentication**

```python
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
from fastapi_session import SessionMiddleware, SocialSession

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="SECRET", auth=SocialSession())

@app.get("/login")
async def login(request: Request):
    redirect_uri = request.url_for("social_callback")
    return RedirectResponse(request.session.get_social_authorization_url(redirect_uri))

@app.get

```
