All Projects → go-chi → Jwtauth

go-chi / Jwtauth

Licence: mit
JWT authentication middleware for Go HTTP services

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Jwtauth

Gin Boilerplate
The fastest way to deploy a restful api's with Gin Framework with a structured project that defaults to PostgreSQL database and JWT authentication middleware stored in Redis
Stars: ✭ 559 (+76.9%)
Mutual labels:  microservices, jwt
Microservices Spring Boot
The source code for series of articles on Medium about Microservices with Spring Boot
Stars: ✭ 382 (+20.89%)
Mutual labels:  microservices, jwt
Micronaut Microservices Poc
Very simplified insurance sales system made in a microservices architecture using Micronaut
Stars: ✭ 394 (+24.68%)
Mutual labels:  microservices, jwt
Spring Boot Jwt
JWT auth service using Spring Boot, Spring Security and MySQL
Stars: ✭ 795 (+151.58%)
Mutual labels:  microservices, jwt
Sample Vertx Microservices
Two applications in different branches illustrates how to create asynchronous microservices with Vert.x, Consul and MongoDB, and how to secure them with Vert.x OAuth2 module and Keycloak
Stars: ✭ 37 (-88.29%)
Mutual labels:  microservices, jwt
Microservices Platform
基于SpringBoot2.x、SpringCloud和SpringCloudAlibaba并采用前后端分离的企业级微服务多租户系统架构。并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手容易,适合学习和企业中使用。真正实现了基于RBAC、jwt和oauth2的无状态统一权限认证的解决方案,面向互联网设计同时适合B端和C端用户,支持CI/CD多环境部署,并提供应用管理方便第三方系统接入;同时还集合各种微服务治理功能和监控功能。模块包括:企业级的认证系统、开发平台、应用监控、慢sql监控、统一日志、单点登录、Redis分布式高速缓存、配置中心、分布式任务调度、接口文档、代码生成等等。
Stars: ✭ 3,274 (+936.08%)
Mutual labels:  microservices, jwt
Framework
Repositório principal contendo o Core e Extensions: JPA, Security, WS
Stars: ✭ 124 (-60.76%)
Mutual labels:  microservices, jwt
Devicehive Java Server
DeviceHive Java Server
Stars: ✭ 241 (-23.73%)
Mutual labels:  microservices, jwt
Go Admin
go web api,包含gin+gorm+jwt+rbac等。
Stars: ✭ 298 (-5.7%)
Mutual labels:  jwt
Nest Angular
NestJS, Angular 6, Server Side Rendering (Angular Universal), GraphQL, JWT (JSON Web Tokens) and Facebook/Twitter/Google Authentication, Mongoose, MongoDB, Webpack, TypeScript
Stars: ✭ 307 (-2.85%)
Mutual labels:  jwt
Angular Spring Starter
Full stack starter kit featuring Angular 7, Spring boot and stateless JWT authentication.
Stars: ✭ 294 (-6.96%)
Mutual labels:  jwt
Memstate
In-memory event-sourced ACID-transactional distributed object graph engine for .NET Standard
Stars: ✭ 280 (-11.39%)
Mutual labels:  microservices
Ilc
Isomorphic Layout Composer - complete solution for Micro Frontends composition into SPA with SSR & i18n support
Stars: ✭ 308 (-2.53%)
Mutual labels:  microservices
Django Rest Framework Jwt
JSON Web Token Authentication support for Django REST Framework
Stars: ✭ 3,105 (+882.59%)
Mutual labels:  jwt
Laravel5 Jsonapi
Laravel 5 JSON API Transformer Package
Stars: ✭ 313 (-0.95%)
Mutual labels:  microservices
Aofe.code
《前端架构:从入门到微前端》源码,code for Architecture of Frontend
Stars: ✭ 292 (-7.59%)
Mutual labels:  microservices
Ruby Jwt
A ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.
Stars: ✭ 3,224 (+920.25%)
Mutual labels:  jwt
Jimu
.netcore micro service framework
Stars: ✭ 315 (-0.32%)
Mutual labels:  jwt
Cqrs
A lightweight enterprise Function as a Service (FaaS) framework to write function based serverless and micro-service applications in hybrid multi-datacentre, on-premise and Azure environments.
Stars: ✭ 310 (-1.9%)
Mutual labels:  microservices
Remoto
Ultra-simple RPC ecosystem designed for right now.
Stars: ✭ 304 (-3.8%)
Mutual labels:  microservices

jwtauth - JWT authentication middleware for HTTP services

GoDoc Widget

The jwtauth http middleware package provides a simple way to verify a JWT token from a http request and send the result down the request context (context.Context).

Please note, jwtauth works with any Go http router, but resides under the go-chi group for maintenance and organization - its only 3rd party dependency is the underlying jwt library "github.com/lestrrat-go/jwx".

In a complete JWT-authentication flow, you'll first capture the token from a http request, decode it, verify it and then validate that its correctly signed and hasn't expired - the jwtauth.Verifier middleware handler takes care of all of that. The jwtauth.Verifier will set the context values on keys jwtauth.TokenCtxKey and jwtauth.ErrorCtxKey.

Next, it's up to an authentication handler to respond or continue processing after the jwtauth.Verifier. The jwtauth.Authenticator middleware responds with a 401 Unauthorized plain-text payload for all unverified tokens and passes the good ones through. You can also copy the Authenticator and customize it to handle invalid tokens to better fit your flow (ie. with a JSON error response body).

By default, the Verifier will search for a JWT token in a http request, in the order:

  1. 'Authorization: BEARER T' request header
  2. 'jwt' Cookie value

The first JWT string that is found as an authorization header or cookie header is then decoded by the lestrrat-go/jwx library and a jwt.Token object is set on the request context. In the case of a signature decoding error the Verifier will also set the error on the request context.

The Verifier always calls the next http handler in sequence, which can either be the generic jwtauth.Authenticator middleware or your own custom handler which checks the request context jwt token and error to prepare a custom http response.

Note: jwtauth supports custom verification sequences for finding a token from a request by using the Verify middleware instantiator directly. The default Verifier is instantiated by calling Verify(ja, TokenFromHeader, TokenFromCookie).

Usage

See the full example.

package main

import (
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/jwtauth/v5"
)

var tokenAuth *jwtauth.JWTAuth

func init() {
	tokenAuth = jwtauth.New("HS256", []byte("secret"), nil)

	// For debugging/example purposes, we generate and print
	// a sample jwt token with claims `user_id:123` here:
	_, tokenString, _ := tokenAuth.Encode(map[string]interface{}{"user_id": 123})
	fmt.Printf("DEBUG: a sample jwt is %s\n\n", tokenString)
}

func main() {
	addr := ":3333"
	fmt.Printf("Starting server on %v\n", addr)
	http.ListenAndServe(addr, router())
}

func router() http.Handler {
	r := chi.NewRouter()

	// Protected routes
	r.Group(func(r chi.Router) {
		// Seek, verify and validate JWT tokens
		r.Use(jwtauth.Verifier(tokenAuth))

		// Handle valid / invalid tokens. In this example, we use
		// the provided authenticator middleware, but you can write your
		// own very easily, look at the Authenticator method in jwtauth.go
		// and tweak it, its not scary.
		r.Use(jwtauth.Authenticator)

		r.Get("/admin", func(w http.ResponseWriter, r *http.Request) {
			_, claims, _ := jwtauth.FromContext(r.Context())
			w.Write([]byte(fmt.Sprintf("protected area. hi %v", claims["user_id"])))
		})
	})

	// Public routes
	r.Group(func(r chi.Router) {
		r.Get("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("welcome anonymous"))
		})
	})

	return r
}

LICENSE

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].