Documentation
¶
Overview ¶
Package passport provides JWT (JSON Web Token) authentication utilities for Hertz.
It uses HS256 (HMAC-SHA256) for token signing and supports custom claims.
Hertz Backend Setup ¶
// Initialize passport
auth := passport.New(
passport.SetKey("your-secret-key-at-least-32-bytes"),
passport.SetIssuer("your-app-name"),
)
// Login endpoint - create JWT token
h.POST("/auth/login", func(ctx context.Context, c *app.RequestContext) {
// ... validate credentials ...
claims := passport.NewClaims(userId, 2*time.Hour).
SetJTI(tokenId).
SetData(map[string]interface{}{"role": "admin"})
token, err := auth.Create(claims)
if err != nil {
c.JSON(500, utils.H{"error": err.Error()})
return
}
c.JSON(200, utils.H{"accessToken": token})
})
// Auth middleware - verify JWT token
func AuthMiddleware(auth *passport.Passport) app.HandlerFunc {
return func(ctx context.Context, c *app.RequestContext) {
token := c.GetHeader("Authorization")
if token == nil {
c.AbortWithStatusJSON(401, utils.H{"error": "missing token"})
return
}
// Remove "Bearer " prefix
tokenStr := strings.TrimPrefix(string(token), "Bearer ")
claims, err := auth.Verify(tokenStr)
if err != nil {
c.AbortWithStatusJSON(401, utils.H{"error": err.Error()})
return
}
c.Set("userId", claims.ActiveId)
c.Set("claims", claims)
c.Next(ctx)
}
}
// Protected routes
api := h.Group("/api", AuthMiddleware(auth))
api.GET("/profile", profileHandler)
Angular Frontend Setup ¶
1. Store token after login:
login(credentials: LoginRequest) {
return this.http.post<{accessToken: string}>('/auth/login', credentials).pipe(
tap(res => localStorage.setItem('token', res.accessToken))
);
}
2. Add token to requests via HTTP interceptor:
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const token = localStorage.getItem('token');
if (token) {
req = req.clone({
setHeaders: { Authorization: `Bearer ${token}` }
});
}
return next(req);
};
3. Register interceptor in app.config.ts:
provideHttpClient(withInterceptors([authInterceptor]))
Security Notes ¶
- Use a strong secret key (at least 32 bytes)
- Set appropriate token expiration time
- Store tokens securely on client side
- Use HTTPS in production
- Consider implementing token refresh for long sessions
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrInvalidSigningMethod = errors.New("passport: invalid signing method, expected HS256") ErrInvalidIssuer = errors.New("passport: token issuer does not match") )
Errors returned by passport functions.
Functions ¶
This section is empty.
Types ¶
type Claims ¶
type Claims struct {
// ActiveId is the primary identifier (usually user ID or session ID).
ActiveId string `json:"active_id,omitempty"`
// Data holds additional custom data.
Data map[string]interface{} `json:"data,omitempty"`
jwt.RegisteredClaims
}
Claims represents the JWT claims with custom fields.
func NewClaims ¶
NewClaims creates a new Claims with the given activeId and expiration duration. It sets IssuedAt and NotBefore to current time.
type Option ¶
type Option func(x *Passport)
Option is a function that configures a Passport instance.
type Passport ¶
Passport provides JWT token creation and verification.
func New ¶
New creates a new Passport instance with the given options. Both SetKey and SetIssuer should be provided for proper operation.