last touch

This commit is contained in:
Gerasimos (Makis) Maropoulos 2020-11-06 11:36:57 +02:00
parent d562f09531
commit f049c51336
No known key found for this signature in database
GPG Key ID: 5DBE766BD26A54E7
2 changed files with 22 additions and 21 deletions

View File

@ -12,30 +12,34 @@ func main() {
app.ConfigureContainer(register)
// http://localhost:8080/authenticate
// http://localhost:8080/restricted
// http://localhost:8080/restricted (Header: Authorization = Bearer $token)
app.Listen(":8080")
}
var (
secret = []byte("secret")
signer = jwt.NewSigner(jwt.HS256, secret, 15*time.Minute)
verify = jwt.NewVerifier(jwt.HS256, secret, jwt.Expected{Issuer: "myapp"}).Verify(func() interface{} {
return new(userClaims)
})
)
var secret = []byte("secret")
func register(api *iris.APIContainer) {
// To register the middleware in the whole api container:
// api.Use(verify)
// Otherwise, protect routes when userClaims is expected on the functions input
// by calling the middleware manually, see below.
api.RegisterDependency(func(ctx iris.Context) (claims *userClaims) {
if ctx.Proceed(verify) { // the "verify" middleware will stop the execution if it's failed to verify the request.
api.RegisterDependency(func(ctx iris.Context) (claims userClaims) {
/* Using the middleware:
if ctx.Proceed(verify) {
// ^ the "verify" middleware will stop the execution if it's failed to verify the request.
// Map the input parameter of "restricted" function with the claims.
return jwt.Get(ctx).(*userClaims)
}*/
token := jwt.FromHeader(ctx)
if token == "" {
ctx.StopWithError(iris.StatusUnauthorized, jwt.ErrMissing)
return
}
return nil
verifiedToken, err := jwt.Verify(jwt.HS256, secret, []byte(token))
if err != nil {
ctx.StopWithError(iris.StatusUnauthorized, err)
return
}
verifiedToken.Claims(&claims)
return
})
api.Get("/authenticate", writeToken)
@ -50,11 +54,8 @@ func writeToken(ctx iris.Context) {
claims := userClaims{
Username: "kataras",
}
standardClaims := jwt.Claims{
Issuer: "myapp",
}
token, err := signer.Sign(claims, standardClaims)
token, err := jwt.Sign(jwt.HS256, secret, claims, jwt.MaxAge(1*time.Minute))
if err != nil {
ctx.StopWithError(iris.StatusInternalServerError, err)
return
@ -63,7 +64,7 @@ func writeToken(ctx iris.Context) {
ctx.Write(token)
}
func restrictedPage(claims *userClaims) string {
func restrictedPage(claims userClaims) string {
// userClaims.Username: kataras
return "userClaims.Username: " + claims.Username
}

View File

@ -119,7 +119,7 @@ var (
// Shortcuts for Signing and Verifying.
var (
VerifyToken = jwt.Verify
Verify = jwt.Verify
VerifyEncryptedToken = jwt.VerifyEncrypted
Sign = jwt.Sign
SignEncrypted = jwt.SignEncrypted