auth

package
v0.11.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2021 License: MIT Imports: 6 Imported by: 0

README

auth使用方法

描述:用户身份认证

安装

go get github.com/hanguangbaihuo/sparrow_cloud_go

配置前提

需要先配置JWT中间件,详见 JWT Middleware

使用方法

import (
	...
	"github.com/hanguangbaihuo/sparrow_cloud_go/middleware/jwt"
	"github.com/hanguangbaihuo/sparrow_cloud_go/middleware/auth"
)

func main() {
    // 初始化iris app
    app := iris.New()
    // 配置jwt中间件
    jwtMiddleware := jwt.DefaultJwtMiddleware("your_jwt_secret")
	app.Use(jwtMiddleware.Serve)
    ...
    // /test 接口需要认证才可以进行
    app.Get("/test", auth.IsAuthenticated, processRequest)
    app.Listen("8081")
}

获取auth User

user := ctx.Values().Get(auth.DefaultUserKey).(auth.User)
// user := ctx.Values().Get("user")
fmt.Println(user.ID, user.IsAuthenticated)

获取token中的其他数据

claimInf := ctx.Values().Get(auth.DefaultClaimsKey).(map[string]interface{})
fmt.Println(claimInf["app_id"])

无需auth中间件获取User

user := auth.CheckUser(ctx)
fmt.Println(user.ID, user.IsAuthenticated)

Documentation

Index

Constants

View Source
const DefaultClaimsKey = "claims"
View Source
const DefaultUserKey = "user"

DefaultUserKey user

Variables

View Source
var (
	// ErrTokenMissing is the error value that it's returned when
	// a token is not found based on the token extractor.
	ErrTokenMissing = errors.New("this api requires authorization token")

	// ErrUserIDMissing is the error value when no user id found in jwt token
	ErrUserIDMissing = errors.New("authorization token missing user id")

	// ErrTokenType when parse jwt token, its type is not available type
	ErrTokenType = errors.New("token type error")
)

Functions

func ErrorHandler

func ErrorHandler(ctx context.Context, err error)

ErrorHandler is the default error handler. Use it to change the behavior for each error.

func IsAuthenticated

func IsAuthenticated(ctx context.Context)

IsAuthenticated is authentication middleware JWT middleware must be configured before this only when your api need be authenticated, you should configure this middleware, otherwise do not configure it

Types

type User

type User struct {
	ID              string
	IsAuthenticated bool
}

User is for authentication

func CheckUser added in v0.5.0

func CheckUser(ctx context.Context) User

CheckUser is a function to check token contains user id, return a User struct

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL