Junior — Middle
Milliseid autentimise ja autoriseerimise mehhanisme te kasutasite oma projektides?
sobes.tech AI
Vastus AI-lt
In Go projects, the following authentication and authorization mechanisms are often used:
- JWT (JSON Web Tokens) — for stateless authentication, where the server issues a token after successful login, and the client sends it in request headers.
- Basic Auth — a simple method of transmitting username and password in headers, usually for internal services.
- OAuth 2.0 — for integration with external providers (Google, Facebook), especially in web applications.
- Middleware for access rights verification — in Go, this is often implemented via middleware that checks for the presence and validity of the token, as well as user permissions.
Example of simple middleware for JWT verification in Go:
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenString := r.Header.Get("Authorization")
if tokenString == "" {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Add token verification logic here
// If token is valid:
next.ServeHTTP(w, r)
})
}