Git Product home page Git Product logo

jose's Introduction

JOSE

Build Status GoDoc

JOSE is a comprehensive set of JWT, JWS, and JWE libraries.

Why

The only other JWS/JWE/JWT implementations are specific to JWT, and none were particularly pleasant to work with.

These libraries should provide an easy, straightforward way to securely create, parse, and validate JWS, JWE, and JWTs.

Notes:

JWE is currently unimplemented.

Version 0.9:

Documentation

The docs can be found at [godoc.org] docs, as usual.

A gopkg.in mirror can be found at https://gopkg.in/jose.v1, thanks to @zia-newversion. (For context, see issue #30.)

License

[MIT] license.

jose's People

Contributors

eliquious avatar ericlagergren avatar ifraixedes avatar magiconair avatar mark-adams avatar supershabam avatar thehippo avatar tooooolong avatar tw1nk avatar yageek avatar zgiber avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jose's Issues

Automatically lookup digital signature algorithm from JWT header

The current API appears to require the user to query the JWT header, then lookup the algorithm based on the name, and finally pass this function reference to Validate().

Could jose do this automatically? This would reduce the risk of mistakes. For example, some users might hardcode the RS256 algorithm, whereas real tokens may use a different algorithm.

Encode object

How can I encode an object from a payload?

type payloadJWT struct {
	exp     int64   'json:"exp"'
	user	string  'json:"user"'
}

func Checktoken(next http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		// test mode
			bytes, _ := ioutil.ReadFile("./cert/jwt.pub")
			rsaPublic, _ := crypto.ParseRSAPublicKeyFromPEM(bytes)
		//

		jwt, err := jws.ParseFromHeader(req, jws.Compact)
		if err != nil {
			log.Fatal(err)
		}

		if err = jwt.Verify(rsaPublic, crypto.SigningMethodRS256); err != nil {
			fmt.Println("O token é inválido.")
			log.Fatal(err)
		} else {
			var payload payloadJWT
			
			//*************************************************
			//jwt.Payload() => payload
			//*************************************************

			fmt.Println("User: ", payload.user)
			next.ServeHTTP(rw, req)
		}

	})
}

jwe eta?

First of all, a big thanks to you for making this clean and easy to understand library, it was a nightmare to work with the other two solutions.

now back on the topic, is there any eta on the JWE implementation?

Typo in docs

In the docs there is a typo: if has 2 "f"s in jwt/eq.go#23

A super tiny error that really doesn't matter that much. Just didn't know where else to report it. Feel free to close if something this small isn't worth fixing.

Enhancement: Convenience method for retrieving scopes

Scopes are a common key in JWT's. Can we get a method with signature like Scopes() ([]string, error), similar to the Issuer() and Audience() methods?

As a workaround, I am carefully reconstructing the scope array from untyped Go interfaces.

Signing JWT via ssh-agent

Is it possible to sign a JWT via ssh-agent instead of having access to the private key which may be locked with a passphrase?

JWK support

It looks like all the code around keys is based around PEM and not JWKs. I'm working on a project that will be using a static JWK Set URL, but some people might also want to use the registered jku JWS header parameter.

Are you familiar with any convenient way to use JWKs as keys using this library? In the past, I used another JOSE library, but this one seems far more mature in terms of feature parity.

Parsing token from a request masks errors

header.go never returns any unmarshaling errors if they were to occur.

// UnmarshalJSON implements json.Unmarshaler for Protected. func (p *Protected) UnmarshalJSON(b []byte) error { var h Header h.UnmarshalJSON(b) *p = Protected(h) return nil }

Does it not make sense to return any unmarshaling errors of the header?
// UnmarshalJSON implements json.Unmarshaler for Protected. func (p *Protected) UnmarshalJSON(b []byte) error { var h Header err := h.UnmarshalJSON(b); if err != nil { return err } *p = Protected(h) return nil }

where are latest api examples?

Most methods of jwt(s)/claims have been deleted? How to use this library?
e.g.

// Create JWS claims  
claims := jws.Claims{}  
claims.SetAudience("example.com", "api.example.com")

I can''t find out SetAudience. and SetIssuedAt, SetNotBefore, SetExpiration

How to parse all three parts: header, payload, signature?

As a developer, I want to be able to easily access each of the three parts of a "JWT": the header, and the payload, as well as the signature bits, as described in various JWT documentation.

https://jwt.io/

jose appears to call the payload portion of JWT's, "JWT", and present the rest of these pieces as "JWS". Furthermore, jose does not make it easy to obtain both the header and the payload, as the existing parser methods only yield one or the other of these attributes. And the payload structure does not appear to nest within the "JWS".

As a workaround, I might end up having to parse my token twice :P

Validation Times out my function

jwt, _ := jws.ParseJWT([]byte(token))
bytes, _ := ioutil.ReadFile("./mypublickey.pub")
rsaPublic, _ := crypto.ParseRSAPublicKeyFromPEM(bytes)
err := jwt.Validate(rsaPublic, crypto.SigningMethodRS256)
if err != nil {
	log.Fatal(err)
	return nil, err
}
jwtToken, _ := jws.Parse([]byte(token))
payload := jwtToken.Payload()
return payload, nil

jwt.Validate <- this part actually times out and logs an error token expired when the token expires. The good thing is that it works .. the bad thing it takes my function to time out which does not allow me to response correctly ...

jwt.io debugger

Hello,

I was just trying to debug a jwt token on http://jwt.io and i cant get it to validate there (Invalid Signature).
i tried both HS256 and RS256 but to no vail, shouldn't it work since it uses the same specification?

Wrong output when serializing JWT

What's the Issue?

The output of JWT.Serialize puts all claims under the "header" object.
The output follows the following format: xxx.yyy (missing .zzz)

How to reproduce?

j := jws.NewJWT(claims, method)
j.Serialize(secret)

Code

claims := jws.Claims{}
claims.SetSubject(u.ID.String())
claims.SetIssuer("tester")
claims.SetIssuedAt(time.Now())
claims.SetExpiration(time.Now().Add(time.Duration(expTimeInMs) * time.Second))
claims.SetAudience("tester")

jwtToken := jws.NewJWT(claims, crypto.SigningMethodHS256)
token, err := jwtToken.Serialize([]byte(secret))

Output

eyJleHAiOjE1ODcxMjE3ODUsImlhdCI6MTU4NzExODE4NSwiaXNzIjoidGVzdGVyIiwic3ViIjoiMjkyZDJiZGYtNzMwZi00YWM3LWEyNTAtMjVlZTA1ZmY0NjBkIn0._uDjvlipGguZbFATXss5f2i4NpEEHPxbhyarDfr1QDA

JWT token validation

Hello. Is there a way to validate that token key matches the original key it was signed with? (As I understand, this is called signature validation). I thought that this code would do the trick:

package main

import (
    "fmt"
    "github.com/SermoDigital/jose/crypto"
    "github.com/SermoDigital/jose/jws"
    "time"
)

func main() {
    mySigningKey := `secret`
    claims := jws.Claims{}
    claims.Set("hello", "world")
    claims.SetExpiration(time.Now().Add(time.Hour * 72))
    claims.SetIssuedAt(time.Now())
    claims.SetIssuer("google.com")
    token := jws.NewJWT(claims, crypto.SigningMethodHS256)
    serializedToken, err := token.Serialize([]byte(mySigningKey))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(serializedToken))

    newToken, err := jws.ParseJWT([]byte(string(serializedToken)))
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(newToken.Validate(mySigningKey, crypto.SigningMethodHS256))
}

But it reports that key is invalid. This validation can also be seen at jwt.io in debugging mode.

How to verify that a token has not been revoked?

Hello, I would like to know more about using this library to verify tokens. Which part of the API should I use in order to communicate with an authentication server to check that a token has not been revoked?

Add patch version to repo tags (v1.1.0 instead of v1.1)

The go mod tool does not recognize SemVersion without the patch version. Therfor it falls back to the v0.9.1 version as its the only tag with patch number in your repo. Could you please tag the repo for v1.1.0 and v1.0.0?

Wrong comparison in Audience validation

I am testing my JWT Factory (GenerateJWT) that receives parameters from a HTTP request.

When comparing parsed claims with the expected claims, the validation will fail because the expected claims is a slice and the parsed one is a string: (I placed a breakpoint at jwt/jwt.go)

(godebug) l

        if jti, ok := v.Expected.JWTID(); ok &&
            j.Claims().Get("jti") != jti {
            return ErrInvalidJTIClaim
        }
-->     _ = "breakpoint"
        if aud, ok := v.Expected.Audience(); ok &&
            !eq(j.Claims().Get("aud"), aud) {
            return ErrInvalidAUDClaim
        }

(godebug) p v.Expected.Audience()
[]string{"report"}, true
(godebug) p j.Claims().Get("aud")
"report"

JWT package have no tests. I can send some PR to fix these bugs and have tests, if they are welcome.

SetExpiration, SetIssuedAt, ... type change

Hey!

First of all: finally a real simple jwt lib! Thanks!

Secondly: as mentioned in the title, should those exported functions receive float64 vars? Can't see any reason why it couldn't be int64.

Compile as a DLL?

Dear Programmers!

Is it somehow possible to compile this code to a binary (DLL or EXE) file, that would work under (XP/) Win7+ ?
Since there is no JWS code for FreePascal/Lazarus, I'm looking for a way to create a wrapper around a finished code.

Library produces (and incorrectly validates) invalid ECDSA signatures

When signing and verifying with ECDSA, this library will take the resulting R and S values and asn1.Marshal them. While the correct behavior for general ECDSA signing (for instance, this is how openssl does it in the general case), for JWS it's actually invalid. See https://tools.ietf.org/html/rfc7515#page-45

The result is that signatures produced on JWTs via this library cannot be validated elsewhere, and signatures produced elsewhere cannot be validated here.

For an example of how other libraries do it, see https://github.com/square/go-jose/blob/16bf7df8a3277fab10a591bc75b9fa0d24e7dab6/asymmetric.go#L511

Suggestion: transfer repo to go-jose/jose

As of right now, the GitHub org go-jose does not exist. It can be created and jose can be transferred to that org, which makes the overall package path: github.com/go-jose/jose

That's desirable because then stable versions of the package can be imported as gopkg.in/jose.v1

As it stands now, either the package github.com/SermoDigital/jose can be imported, which will download the package as it is on master branch. If one wants the v1 branch, they would do something like github.com/SermoDigital/jose/tree/v1 which does not quite work when importing said package. Another option would be to use gopkg.in/SermoDigital/jose.v1 which works, and that is what I'm using right now. But gopkg.in/jose.v1 is shorter, and much better IMO.

claims.SetExpiration undefined (type jws.Claims has no field or method SetExpiration)

Hi,
I am trying to set exp.
I used this code as inpsitarion: https://github.com/SermoDigital/jose/blob/master/jwt/claims_test.go
I did:

go get github.com/SermoDigital/jose
package main

import (
	"fmt"
	"time"

	"github.com/SermoDigital/jose/jws"
)

func main() {
	// expires in 10 seconds
	expires := time.Now().Add(time.Duration(10) * time.Second)

         // set exp
	claims := jws.Claims{}
	claims.SetExpiration(expires)

	fmt.Println(claims)
}

But i get the following erros messages when i run the code.

claims.SetExpiration undefined (type jws.Claims has no field or method SetExpiration)

I am new to Go.
Help is highly appreciated.

Error with raw JWT from jwt.io

I created some JWT from https://jwt.io with some scope payload:

{
  "scopes": [
    "test",
    "test2"
  ]
}

The resulted token value is: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZXMiOlsidGVzdCIsInRlc3QyIl19.03T1Fi7AE6GsJW_wdvB1faqoT69UeEBEj0J5RCjLxD4
Then I wanted to use the Claims() function to recover the scopes array from the token.

c := token.Claims()
scopesPayload := c.Get("scopes")
if scopesPayload == nil {
    http.Error(rw, "No scopes provided", http.StatusBadRequest)
    return
}

userScopes, ok := scopesPayload.([]string)
if !ok {
   http.Error(rw, "No valid scopes provided", http.StatusBadRequest)
return
}

The type assertion never work in my case and the ok value is never true.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.