Giter Club home page Giter Club logo

jsonwebtoken.swift's Introduction

JSON Web Token

Build Status

Swift implementation of JSON Web Token.

Installation

Swift Pacakage Manager is the recommended installation method for JSONWebToken, CocoaPods is also supported.

pod 'JSONWebToken'

NOTE: Carthage may be supported, however support will not be provided for this installation method, use at your own risk if you know how it works.

Usage

import JWT

Encoding a claim

JWT.encode(claims: ["my": "payload"], algorithm: .hs256("secret".data(using: .utf8)!))

Encoding a claim set

var claims = ClaimSet()
claims.issuer = "fuller.li"
claims.issuedAt = Date()
claims["custom"] = "Hi"

JWT.encode(claims: claims, algorithm: .hs256("secret".data(using: .utf8)!))

Building a JWT with the builder pattern

JWT.encode(.hs256("secret".data(using: .utf8))) { builder in
  builder.issuer = "fuller.li"
  builder.issuedAt = Date()
  builder["custom"] = "Hi"
}

Decoding a JWT

When decoding a JWT, you must supply one or more algorithms and keys.

do {
  let claims: ClaimSet = try JWT.decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.2_8pWJfyPup0YwOXK7g9Dn0cF1E3pdn299t4hSeJy5w", algorithm: .hs256("secret".data(using: .utf8)!))
  print(claims)
} catch {
  print("Failed to decode JWT: \(error)")
}

When the JWT may be signed with one out of many algorithms or keys:

try JWT.decode("eyJh...5w", algorithms: [
  .hs256("secret".data(using: .utf8)!),
  .hs256("secret2".data(using: .utf8)!),
  .hs512("secure".data(using: .utf8)!)
])

You might also want to give your iat, exp and nbf checks some kind of leeway to account for skewed clocks. You can do this by passing a leeway parameter like this:

try JWT.decode("eyJh...5w", algorithm: .hs256("secret".data(using: .utf8)!), leeway: 10)

Supported claims

The library supports validating the following claims:

  • Issuer (iss) Claim
  • Expiration Time (exp) Claim
  • Not Before (nbf) Claim
  • Issued At (iat) Claim
  • Audience (aud) Claim

Algorithms

This library supports the following algorithms:

  • none - Unsecured JWTs
  • hs256 - HMAC using SHA-256 hash algorithm (default)
  • hs384 - HMAC using SHA-384 hash algorithm
  • hs512 - HMAC using SHA-512 hash algorithm

License

JSONWebToken is licensed under the BSD license. See LICENSE for more info.

jsonwebtoken.swift's People

Contributors

a2 avatar ahernandezlopez avatar deekor avatar gtchance avatar hamchapman avatar ikesyo avatar janbrinker avatar jjb3rd avatar jonblatho avatar kylef avatar maxfell avatar parrots avatar pyyoshi avatar segiddins avatar shanev avatar siemensikkema avatar tternes 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

jsonwebtoken.swift's Issues

"Issued at claim (iat) is in the future" error when using device, but not on the simulator.

If I run my app in the Simulator I receive no errors and JSONWebToken decodes the server's JWT with no problem (node server is running on my localhost). However, when i run the app on my iPhone i get the error "Issued at claim (iat) is in the future". I've been troubleshooting for a couple hours now, I updated by CryptoSwift and JSONWebToken with no luck. Any ideas?

Requesting new release tag (2.1.1) for SwiftPM

Currently, the latest release v2.1.0 doesn't include the PR (which adds the correct Foundation imports to ClaimSet.swift and Encode.swift) causing build errors. If you don't mind releasing a new version (v.2.1.1), that'd be great 👍

Swift packager install fails

error: rename error: Directory not empty (66): /Users/x/dev/p/server/Packages/CryptoSwift.git -> /Users/x/dev/p/server/Packages/CryptoSwift-0.6.7

Difference Swift 3.0 and Swift 2.0 release

I adopted to Swift 3.0 and figured out to make it work correctly. The signature gets verified if I set "secret base64 encoded" to true.

Here the code:

let secret = Data(base64Encoded: "My20CharSecret", options: [])
return JWT.encode(["userid": userID], algorithm: .hs256(secret! as Data))

Now I want to do the same for an old Swift 2.2 project.
Here the signature is only valid if I uncheck "secret base64 encoded".
Here the code:
return JWT.encode(["userid": userID], algorithm: .HS256("My20CharSecret"))

What do I have to do to get a verification with the "secret base64 encoded" checked?

Use carthage to install

I try Carthage to install this module using in cartfile:

github "kylef/JSONWebToken.swift"

but on carthage update --platform iOS

I receive the error:

Dependency "JSONWebToken.swift" has no shared framework schemes for any of the platforms: iOS

Can you help me?
Thanks.

can't pod in tvos project

[!] The platform of the target Movie4Free (tvOS 9.0) is not compatible with JSONWebToken (1.4.1), which does not support tvos.

please help.

Problem with "krzyzanowskim/CryptoSwift"

I have a project with both "krzyzanowskim/CryptoSwift" and "kylef/JSONWebToken.swift".
But the latest version of CryptoSwift is 0.6.8 and the latest used by JSONWebToken is 0.6.1, so at runtime it uses the 0.6.1 and I receive :

Message from debugger: Terminated due to signal 9

decoding fails for a JWT generated with java library

The decoding of below jwt token is failing with an error: Invalid algorithm. I have used HS256 as the algorithm and my signing secret is 'pratik'. Issuer is blank. I am using version 1.4.0 since I am running with swift 2.0.

eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJpZDEiLCJpYXQiOjE0NjUyNTgzODcsInN1YiI6InN1YmplY3QxIn0.up3EiW_4feVcgfBvVEiPiVDiAZLeMnRRfu6sqLne3E0

token is too long

i'm call encode to make a token, but the token is too long.

and i'm use node.js to make a token, but the token is too short.

Support for Swift 4

Currently support for Swift 4 is not given due to the dependency CryptoSwift. It was solved already though in the develop branch and I'm sure a release is gonna be made soon. Until then I created #75 for all who can't wait to solve this issue.

Adding to the Header

You hardcode the header like this in Encode.swift

let header = encodeJSON(["typ": "JWT", "alg": algorithm.description])!

The new Apple MusicKit framework requires a key "kid" in the header.
Since there doesn't seem to be a way to add to the header, I had to make the modification in Encode.swift.

Consider adding this capability to your library.

See MusicKit

Error While Installing via CocoaPods

I have installed the 'JSONWebToken' via CocoaPods but can't build due to some errors in file CryptoSwift framework. Attached the error screen shot.
I am using CocoaPod version 1.0.1

pod install installs version 2.0.2 and not 2.1.0

Hi there

2.1.0 does not install via pod (using cocoapod 1.2.0)

I've tried 'pod repo update' before 'pod install' and I have also tried changing the podfile.lock entry from:
'JSONWebToken (2.0.2):
- CryptoSwift (> 0.6.1)'
to:
'JSONWebToken (2.1.0):
- CryptoSwift (
> 0.6.1)'

but get the error: _[!] Unable to satisfy the following requirements:

  • JSONWebToken required by Podfile
  • JSONWebToken (= 2.1.0) required by Podfile.lock

None of your spec sources contain a spec satisfying the dependencies: JSONWebToken, JSONWebToken (= 2.1.0).

You have either:

  • out-of-date source repos which you can update with pod repo update.
  • mistyped the name or version.
  • not added the source repo that hosts the Podspec to your Podfile._

More information below:

Included in my pod file:
pod 'JSONWebToken’

running 'pod install' generates:

Using JSONWebToken (2.0.2)
Generating Pods project
Integrating client project
Sending stats

podfile.lock

PODS:

  • CryptoSwift (0.6.7)
  • Firebase/Core (3.14.0):
    • FirebaseAnalytics (= 3.7.0)
    • FirebaseCore (= 3.5.1)
  • Firebase/Database (3.14.0):
    • Firebase/Core
    • FirebaseDatabase (= 3.1.2)
  • FirebaseAnalytics (3.7.0):
    • FirebaseCore (~> 3.5)
    • FirebaseInstanceID (~> 1.0)
    • GoogleToolboxForMac/NSData+zlib (~> 2.1)
  • FirebaseCore (3.5.1):
    • GoogleToolboxForMac/NSData+zlib (~> 2.1)
  • FirebaseDatabase (3.1.2):
    • FirebaseAnalytics (~> 3.7)
  • FirebaseInstanceID (1.0.9)
  • GoogleToolboxForMac/Defines (2.1.1)
  • GoogleToolboxForMac/NSData+zlib (2.1.1):
    • GoogleToolboxForMac/Defines (= 2.1.1)
  • JSONWebToken (2.0.2):
    • CryptoSwift (~> 0.6.1)

DEPENDENCIES:

  • Firebase/Core
  • Firebase/Database
  • JSONWebToken

SPEC CHECKSUMS: ...........

Carthage support?

I don't like the way CocoaPods works that is to intrusive. I tried to build this library using carthage, but it doesn't build. Is it possible to make this library to support carthage? Here is the error message when I tried to build with carthage:

*** Building scheme "JWT" in JWT.xcworkspace
** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/elgs/Library/Developer/Xcode/DerivedData/JWT-aqboxwyfwmewxqhiljchyebefxbh/Build/Intermediates/JWT.build/Release/JWT.build/Script-4B9936F743EA727EA58353BD.sh
(1 failure)
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
A shell task failed with exit code 65:
** BUILD FAILED **


The following build commands failed:
    PhaseScriptExecution Check\ Pods\ Manifest.lock /Users/elgs/Library/Developer/Xcode/DerivedData/JWT-aqboxwyfwmewxqhiljchyebefxbh/Build/Intermediates/JWT.build/Release/JWT.build/Script-4B9936F743EA727EA58353BD.sh
(1 failure)

Can't use Swift Package Manager as described in README

Using:

import PackageDescription

let package = Package(
  name: "AwesomeProject",
  dependencies: [
    .Package(url: "https://github.com/kylef/JSONWebToken.swift", versions: Version(1,4,2)..<Version(1,5,0))
  ]
)

Results in:

Downloading dependencies...
Cloning https://github.com/kylef/JSONWebToken.swift
error: The dependency graph could not be satisfied. The package (https://github.com/kylef/JSONWebToken.swift) with version tag in range (1.4.2..<1.5.0) is not found. Found tags ([1.0.0, 1.0.1, 1.1.0, 1.2.0, 1.3.0, 1.4.0, 1.4.1])

The repo has no tag for 1.4.2.

Not all classes being downloaded with the Pod

I installed JWT through cocoapods. pod 'JSONWebToken'. The example tells me to use the ClaimSet class, which isn't downloaded. The only classes downloaded are Base64, Claims, JWT, and Decode. Xcode doesn't recognize any other classes mentioned in the guides (makes sense, since they don't appear in my pod workspace either).

CryptoSwift version is too low

CryptoSwift version is too low,when to update to the lately version.
when i'm pod update, now

  • CryptoSwift (= 0.2.3) required by Podfile
  • CryptoSwift (= 0.2.3) required by Podfile
  • CryptoSwift (= 0.2.3) required by Podfile
  • CryptoSwift (~> 0.0.8) required by JSONWebToken (1.0.0)

some errors like this

Xcode 9 beta 5 build failed

Xcode 9 beta 5, swift 3.2 with carthage version 0.23.0, currently using "kylef/JSONWebToken.swift" "2.1.0" version. fails building CryptoSwift

watchOS error with Carthage

Xcode: 8.0 (8A218a)
Sierra 10.12
JSONWebToken.swift version 2.0.1

Cartfile:

github "kylef/JSONWebToken.swift" == 2.0.1

Cartfile.resolved:

github "krzyzanowskim/CryptoSwift" "0.6.0"
github "kylef/JSONWebToken.swift" "2.0.1"

When using Carthage to install the library (running carthage update I'm getting this error, in relation to CryptoSwift.

/DerivedData/JWT-grekwtpopyeadqfzzrcglfxcjnno/Build/Intermediates/JWT.build/Release-watchos/JWT-watchOS.build/Objects-normal/armv7k/Base64.bc
/Users/Hami/Pusher/elements-client-swift/Carthage/Checkouts/JSONWebToken.swift/Sources/JWT.swift:2:8: error: module file's minimum deployment target is watchos3.0 v3.0: /Users/Hami/Library/Developer/Xcode/DerivedData/JWT-grekwtpopyeadqfzzrcglfxcjnno/Build/Products/Release-watchos/CryptoSwift.framework/Modules/CryptoSwift.swiftmodule/arm.swiftmodule
import CryptoSwift
       ^

** BUILD FAILED **


The following build commands failed:
    CompileSwift normal armv7k /Users/Hami/Pusher/elements-client-swift/Carthage/Checkouts/JSONWebToken.swift/Sources/Claims.swift
    CompileSwift normal armv7k /Users/Hami/Pusher/elements-client-swift/Carthage/Checkouts/JSONWebToken.swift/Sources/JWT.swift
    CompileSwift normal armv7k /Users/Hami/Pusher/elements-client-swift/Carthage/Checkouts/JSONWebToken.swift/Sources/Decode.swift
    CompileSwift normal armv7k /Users/Hami/Pusher/elements-client-swift/Carthage/Checkouts/JSONWebToken.swift/Sources/Base64.swift
    CompileSwiftSources normal armv7k com.apple.xcode.tools.swift.compiler
(5 failures)

The target I'm trying to add this to is a target with support for iOS, tvOS, macOS and watchOS.

IAT is an int but it says it's not

Hello,

When I decode my JWT I got this error:

Decode Error: Issued at claim (iat) must be an integer

But the problem is that the iat is actually an integer. If I do a println of payload[key] in the validateDate function, it returns: Optional(1433003301)

What is the problem ?

Subject (sub) claim

I was hoping that I would be able to create tokens within the app to create a custom login to Firebase 3. However this requires that the Subject (sub) claim be set as per below:

"sub Subject Must be a non-empty string and must be the uid of the user or device."

Is this something that can be supported please?

Difference between JWT Tokens

I'm currently trying to generate a simple JWT, where the only payload is a expiration date. However, my implementation when trying to use this library appears to generate a different token than when when I use https://github.com/yourkarma/JWT or when checking jwt.io (these two are consistent with each other).

Using the CocoaPods Playgrounds gem (gem install cocoapods-playgrounds), I tried out both of them, using equivalent implementations (as far as I can tell).

JSONWebToken

// After installing the gem, use `pod playground JSONWebToken` to generate a playground quickly.

//: Please build the scheme 'JWTPlayground' first
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

import JWT

let secret = "DevelopmentTestJWTSecret1"

var claims = ClaimSet()
claims.expiration = Date.distantFuture

let token = JWT.encode(claims: claims, algorithm: .hs256(secret.data(using: .utf8)!))
print(token)
// prints eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjY0MDkyMjExMjAwfQ.uk571j2rhEXAO_5K2AjGKLgPd6WaIAUVAioontTdVIs

Your Karma's JWT

// After installing the gem, use `pod playground JWT` to generate a playground quickly.

//: Please build the scheme 'JWTPlayground' first
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true

import JWT

let secret = "DevelopmentTestJWTSecret1"
let algorithm = JWTAlgorithmFactory.algorithm(byName: "HS256")

var claims = JWTClaimsSet()
claims.expirationDate = Date.distantFuture

let token = JWT.encode(claims, withSecret: secret, algorithm: JWTAlgorithmHS256())
print(token!)
// prints eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjY0MDkyMjExMjAwfQ.qOIoSj36uxELKwl3uejese_IBpAeEw36WQ9mmeOYk0A

jwt.io

Filling in the above settings in jwt.io, gives me the following key, which is equivalent to JWT's result;

// prints eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjY0MDkyMjExMjAwfQ.qOIoSj36uxELKwl3uejese_IBpAeEw36WQ9mmeOYk0A

screen shot 2017-05-31 at 19 05 58

(Take care with the order of typ and alg in the website. By default, they appear to show it the other way around.)


I'm thinking I'm filling in something wrong, but I can't spot it.

Any idea why the result for JSONWebToken is different?

Support for Swift 2.1

Hi ,
can you please provide version of lib that support swift 2.1 ? It would be of G8 help !

Build Failed on Xcode 9 Beta 6

It shows No module found, and CyptoSwift files appears with many syntax error. I have tried to install it on Xcode 8 and it worked fine. But I am trying to use the Apple Music API which requires Xcode 9 Beta 6, can you confirm the error when you have time, please? Thank you

Ambiguous use of decode (v. 2.1.0)

Hello.

After an upgrade from JSONWebToken 2.0.1 to 2.1.0

I get the following error:
Ambiguous use of 'decode(_:algorithm:verify:audience:issuer:)'

My code
let payload = try JWT.decode(cryptedResponse, algorithm: .hs256((api.key).data(using: .utf8)!))

And when I click on "decode", XCode leads me to this
typedef struct vImage_CGImageFormat { uint32_t bitsPerComponent; uint32_t bitsPerPixel; CGColorSpaceRef colorSpace; CGBitmapInfo bitmapInfo; uint32_t version; const CGFloat * decode; CGColorRenderingIntent renderingIntent; }vImage_CGImageFormat;

Which has nothing to do with JWT, but with the Accelerate framework (that I don't use...).

I've tried to clean the project, removed the derived data, and even upgraded my XCode from 8.1 to 8.2, but still ...

I finally downgraded your lib from 2.1.0 to 2.0.2, and the error is gone.

Hope this report can help.

Thanks.

JWT headers

Is there currently a way to adjust the header / insert a new value into it?

Get Raw ClaimSet Data

I'm using let payload: Payload = try JWT.decode(...) to get the dictionary data to pass off to a 3rd party library. I'm getting a deprecated notice so I try let claimSet: ClaimSet = JWT.decode(...); claimSet.claims but get the error 'claims' is inaccessible due to 'internal' protection level.

EDIT: Forgot to mention I'm using Carthage.

How can I install without CocoaPods?

I want to use the project without the dependency of CocoaPods in my project. I have copied the following files:

Base64.swift
Claims.swift
Decode.swift
JWT.swift

But I am getting errors for import CryptoSwift

From the JWT Xcode project what all do I need to copy to getting it running? Thank you!

Make algorithm parameter optional for decode

decode only needs an algorithm if verify is true, otherwise it never even touches the algorithm parameter. This means even when I'm not verifying the JWT, I have to pass some sort of algorithm who's values are of no consequence.

I think even passing Algorithm.None is slightly misleading, because a JWT can be encoded using Algorithm.None, so there's still an implication that something will be done with this argument.

Therefore, may I propose making the algorithm parameter optional for decode?

Support for swift 3.1 on Linux

The encode function gives a runtime error on linux

*** Error in `./.build/debug/Test': free(): invalid size: 0x0000000001df9670 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fc91d5b17e5]
/lib/x86_64-linux-gnu/libc.so.6(+0x7fe0a)[0x7fc91d5b9e0a]
/lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fc91d5bd98c]
/home/sujay/swift/swift-3.1-RELEASE-ubuntu16.04/usr/lib/swift/linux/libFoundation.so(_TFC10Foundation6NSData17base64EncodedDatafT7optionsVS0_21Base64EncodingOptions_VS_4Data+0x1b5)[0x7fc91ec26ef5]
/home/sujay/swift/swift-3.1-RELEASE-ubuntu16.04/usr/lib/swift/linux/libFoundation.so(_TFV10Foundation4Data17base64EncodedDatafT7optionsVCS_6NSData21Base64EncodingOptions_S0_+0x13b)[0x7fc91eee0adb]
./.build/debug/Test[0x4a0ca1]
./.build/debug/Test[0x49dccd]
./.build/debug/Test[0x49d9ad]
./.build/debug/Test[0x49e310]
./.build/debug/Test[0x40d569]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fc91d55a830]
./.build/debug/Test[0x40ccf9]
======= Memory map: ========

Build failing on linux

I have ubuntu 16 and the terminal shows this error while building

/Packages/JWT-2.0.1/Sources/JWT.swift:84:84: 
error: 'String' is not convertible to 'AnyObject'; 
did you mean to use 'as!' to force downcast?
  let header = encodeJSON(["typ": "JWT" as AnyObject, 
"alg": algorithm.description as AnyObject])!

Header values are in diferent order

In most of JWT implementations in other languages the header start with typ property and after alg. Why in swift alg property on header is first?

Cannot find JWT

I installed the framework with cocoa pods in the time being while issue #31 is resolved.
When I import JWT and then try to use JWT it can not be found. There is no autocomplete and I can not use the decode or encode methods. I am on Xcode 7.3 Swift 2.2. I have not errors when I build and I can run but the JWT framework methods are not exposed.

Updated

If you create a struct and try to call JWT it throws error expected declaration.

Swift 3 support

Are you planning to add swift3 support?
It's in beta now but many packages already have swift3 branches.

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.