Authentication with Axum

https://news.ycombinator.com/rss Hits: 17
Summary

Authentication with Axum May 3, 2025 Consider this scenario: you’re building a website that has a classic navbar at the top, this navbar has a button that reflects the user authentication status, showing a "Profile" button if the user is authenticated and showing a "Login" button in case the user is unauthenticated. This is a very common scenario, let’s sketch something quick using axum and askama. <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {% block head %}{% endblock %} </head> <body> <nav> <div> <div> {% if ctx.authed %} <a href="/profile">Profile</a> {% else %} <a href="/login">Login</a> {% endif %} </div> </div> </nav> {% block content %} {% endblock %} </body> </html> This will be our layout.jinja file that we can build upon. The template above would be served by an endpoint that looks like the following #[derive(Debug, Default)] pub struct Context { authed: bool, } #[derive(Template)] #[templage = "layout.jinja"] struct HomeTemplate { ctx: Context }; pub async fn home() -> impl IntoResponse { HtmlTemplate( HomeTemplate { ctx: Context::default() } ).into_response() } We have something to work with, all is missing is a way derive a Context from a user’s HTTP request. I’d argue the simplest way to handle user authentication if you’re doing SSR is using cookies. Cookies are a cornerstone of backend authentication because they’re reliable, browser-managed, and can be hardened with specific attributes to mitigate common security risks. Here’s why: HttpOnly Attribute: Prevents client-side JavaScript from accessing the cookie, neutralizing XSS attacks. If an attacker injects malicious scripts, they can’t steal your session cookie. Secure Attribute: Ensures the cookie is only sent over HTTPS, protecting it from interception on insecure networks (e.g., public Wi-Fi). SameSite Attribute: Mitigates CSRF (Cross-Site Request Forgery) ...

First seen: 2025-06-05 01:48

Last seen: 2025-06-05 17:57