Skip to main content

jwt-authentication-mechanism

table-of-contents

  1. introduction
  2. project-structure
  3. core-components
  4. architecture-overview
  5. component-details
  6. dependency-analysis
  7. performance-considerations
  8. troubleshooting-guide
  9. conclusion
  10. appendix

introduction

this document systematically organizes the jwt authentication mechanism in the repository, covering the following topics:

  • jwt token structure and claims design
  • principal identity information carrying and transmission
  • token generation algorithm, signature verification, and expiration time management
  • middleware implementation principles: request interception, token parsing, authentication flow
  • configuration items, security best practices, and common issue troubleshooting
  • practical integration examples: using jwt authentication in http requests, refresh and renewal

project-structure

key modules related to jwt are distributed as follows:

  • authentication domain model and utilities: claims, principal, token, token generator, rsa-related capabilities
  • http middleware: jwt authentication middleware
  • bootstrap and assembly: authorization unified registration of middleware and token generator
  • session-related: session entity, service and routing/handlers (cooperating with jwt)
  • userclaims: extends registeredclaims, adds user identifier and role array, serves as custom claims for jwt.
  • principal: encapsulates current request identity information (username, userid, roles), transmitted through context.
  • token: uniformly returns access token, refresh token, scope, and expiration interval.
  • tokengenerator: token generator interface and implementation, responsible for generating access/refresh tokens, refresh flow, and signing.
  • jwtauthmiddleware: gin middleware, responsible for parsing and validating jwt from authorization header, injecting principal.
  • authorization: bootstrap layer aggregates tokengenerator and middleware, facilitating centralized registration.

the following diagram shows the key path from request entering the application to completing identity authentication, as well as collaboration with the session system.

claims-declaration-design-userclaims

  • inherits registeredclaims, built-in issuer, subject, expiration time, effective time, issuance time, etc.
  • extended-fields: userid, role list, facilitating extraction and principal injection in middleware.
  • default-expiration-time-set-in-constructor,-can-be-overridden-when-generating-access-token.
  • use-context.context-to-pass-current-principal-in-key-value-form.
  • after-middleware-validation-passes,-write-principal-to-request-context-for-subsequent-handlers-to-extract-through-utility-functions.
  • interface-responsibilities:-generate-token-pair(access+refresh),-generate-pure-jwt-string,-refresh-token.
  • generation-strategy:
    • access-token:-set-according-to-generator-configured-expiration-time.
    • refresh-token:-set-according-to-refresh-expiration-time.
  • refresh-flow:-parse-refresh-token->-validate-validity->-update-issuance-time-to-current-time->-regenerate-new-token-pair.
  • request-interception:-parse-bearer-token-from-authorization-header.
  • parsing-and-validation:-use-userclaims-type-to-parse,-validate-signature-method-and-key;-use-v5-error-auxiliary-functions-to-distinguish-error-types.
  • context-injection:-after-validation-passes,-inject-principal-into-request-context-for-subsequent-handlers-to-use.
  • error-handling:-return-clear-401-responses-for-format-errors,-expiration,-invalid-signatures,-etc.
  • session-entity-and-service-provide-ttl-based-expiration-management,-can-be-used-for-session-level-state-storage.
  • routing-and-handlers-support-session-creation,-query,-update,-and-deletion,-can-cooperate-with-jwt-access-token-to-implement-session-lifecycle-management.
  • provide-noncestore,-publickeyprovider,-signaturecache-interfaces-and-default-configurations,-used-for-rsa-based-request-authentication-and-replay-prevention.

  • complementary-to-hs256-jwt-authentication,-suitable-for-scenarios-with-higher-security-requirements.

  • middleware-depends-on-keys-and-claims-types-generated-by-tokengenerator,-ensuring-consistency-in-parsing-and-validation.

  • principal-decouples-from-middleware-through-context,-facilitating-reuse-in-various-handlers.

  • bootstrap-layer-authorization-unifies-registration-of-tokengenerator-and-middleware,-simplifying-assembly.

  • hs256-signature-overhead-is-low,-suitable-for-high-concurrency-scenarios;-if-stronger-non-repudiation-is-needed,-can-combine-with-rsa-authentication.
  • refresh-token-and-access-token-separation,-reduces-frequent-issuance-costs;-suggest-reasonably-setting-refresh-expiration-time-to-avoid-risks-from-long-term-validity.
  • middleware-only-performs-necessary-validation-and-context-injection,-avoiding-introducing-additional-io-in-the-chain.

troubleshooting-guide

  • common-errors-and-handling
    • missing-authorization-header-or-incorrect-format:-middleware-directly-returns-401.
    • token-format-error,-expired,-not-yet-effective,-invalid-signature:-return-clear-information-based-on-v5-error-auxiliary-functions.
    • tokens-using-wrong-signature-methods-(such-as-rs256):-middleware-will-identify-and-deem-invalid.
  • refresh-token-failure
    • confirm-refresh-token-has-not-expired-and-signature-is-correct.
    • ensure-generator-used-key-is-consistent-with-middleware.
  • context-not-injected-principal
    • check-if-middleware-is-correctly-registered-to-route.
    • confirm-request-header-authorization-format-is-bearer-token.

this-implementation-implements-jwt-authentication-in-a-concise-and-clear-way:-carrying-identity-and-roles-through-userclaims,-completing-token-generation-and-refresh-through-tokengenerator,-jwtauthmiddleware-completes-parsing-and-validation-at-entry-point-and-injects-principal-into-context.-cooperating-with-session-system-can-further-improve-session-lifecycle-management.-overall-design-follows-clean-architecture-layering,-easy-to-extend-and-maintain.

appendix

configuration-options-and-best-practices

  • token-expiration-time
    • access-token:-suggest-shorter-(such-as-1-hour),-improve-security.
    • refresh-token:-suggest-longer-(such-as-24-hours),-but-need-to-limit-refresh-counts-and-sources.
  • key-management
    • hs256:-use-strong-random-keys,-properly-store,-regularly-rotate.
    • if-stronger-non-repudiation-is-needed,-can-combine-with-rsa-authentication.
  • middleware-usage
    • register-jwtauthmiddleware-on-routes,-ensure-protected-resources-are-all-validated.
    • in-handlers-extract-principal-from-context-through-utility-functions-for-permission-control.
  • refresh-and-renewal
    • client-uses-refresh-token-to-exchange-for-new-token-pair,-old-token-can-still-continue-to-be-used-until-expiration-(depends-on-business-policy).
    • suggest-replacing-client-held-access-token-and-refresh-token-after-successful-refresh.

practical-usage-examples-(step-instructions)

  • generate-token-pair
    • use-tokengenerator.granttoken(claims,-scope)-to-generate-access-and-refresh-tokens.
    • access-token-expiration-time-determined-by-generator-configuration;-refresh-token-expiration-time-set-separately.
  • send-request
    • use-bearer-scheme-in-authorization-request-header-to-carry-access-token.
  • refresh-token
    • when-access-token-is-about-to-expire-or-has-expired,-client-uses-refresh-token-to-call-refresh-interface-to-get-new-token-pair.
  • session-management
    • can-combine-with-session-entity-and-service,-persist-user-state-in-session,-cooperate-with-jwt-access-token-to-implement-session-lifecycle-management.