Giter Club home page Giter Club logo

jwtdecode.swift's Introduction

JWTDecode.swift

Version Build Status Coverage Status License

📚 Documentation • 🚀 Getting Started • 📃 Support Policy • 💬 Feedback

This library doesn't validate the JWT. Any well-formed JWT can be decoded from Base64URL.

Migrating from v2? Check the Migration Guide.

Documentation

Important

Check the Support Policy to learn when dropping Xcode, Swift, and platform versions will not be considered a breaking change.

Getting Started

Requirements

  • iOS 13.0+ / macOS 11.0+ / tvOS 13.0+ / watchOS 7.0+
  • Xcode 14.x / 15.x
  • Swift 5.7+

Installation

Swift Package Manager

Open the following menu item in Xcode:

File > Add Packages...

In the Search or Enter Package URL search box enter this URL:

https://github.com/auth0/JWTDecode.swift

Then, select the dependency rule and press Add Package.

Cocoapods

Add the following line to your Podfile:

pod 'JWTDecode', '~> 3.1'

Then, run pod install.

Carthage

Add the following line to your Cartfile:

github "auth0/JWTDecode.swift" ~> 3.1

Then, run carthage bootstrap --use-xcframeworks.

Usage

See all the available features in the API documentation ↗

  1. Import the framework
import JWTDecode
  1. Decode the token
let jwt = try decode(jwt: token)    

JWT parts

Part Property
Header dictionary jwt.header
Claims in JWT body jwt.body
JWT signature jwt.signature

Registered claims

Claim Property
aud Audience jwt.audience
sub Subject jwt.subject
jti JWT ID jwt.identifier
iss Issuer jwt.issuer
nbf Not Before jwt.notBefore
iat Issued At jwt.issuedAt
exp Expiration Time jwt.expiresAt

Custom claims

You can retrieve a custom claim through a subscript and then attempt to convert the value to a specific type.

if let email = jwt["email"].string {
    print("Email is \(email)")
}

The supported conversions are:

var string: String?
var boolean: Bool?
var integer: Int?
var double: Double?
var date: Date?
var array: [String]?

You can easily add a convenience accessor for a custom claim in an extension.

extension JWT {
    var myClaim: String? {
        return self["my_claim"].string
    }
}

Error handling

If the JWT is malformed the decode(jwt:) function will throw a JWTDecodeError.

catch let error as JWTDecodeError {
    print(error)
}

Support Policy

This Policy defines the extent of the support for Xcode, Swift, and platform (iOS, macOS, tvOS, and watchOS) versions in JWTDecode.swift.

Xcode

The only supported versions of Xcode are those that can be currently used to submit apps to the App Store. Once a Xcode version becomes unsupported, dropping it from JWTDecode.swift will not be considered a breaking change, and will be done in a minor release.

Swift

The minimum supported Swift minor version is the one released with the oldest-supported Xcode version. Once a Swift minor becomes unsupported, dropping it from JWTDecode.swift will not be considered a breaking change, and will be done in a minor release.

Platforms

Once a platform version becomes unsupported, dropping it from JWTDecode.swift will not be considered a breaking change, and will be done in a minor release. For example, iOS 13 will cease to be supported when iOS 17 gets released, and JWTDecode.swift will be able to drop it in a minor release.

In the case of macOS, the yearly named releases are considered a major platform version for the purposes of this Policy, regardless of the actual version numbers.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

jwtdecode.swift's People

Contributors

adolfo avatar bchrobot avatar cocojoe avatar cristiandouce avatar damieng avatar dependabot[bot] avatar ericbuehl avatar evansims avatar fossabot avatar hzalaz avatar jklp avatar joshcanhelp avatar kaishin avatar lbalmaceda avatar mgonto avatar narlei avatar ntotten avatar obrhoff avatar pose avatar snyk-bot avatar sre-57-opslevel[bot] avatar stevehobbsdev avatar widcket avatar wkoszek 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwtdecode.swift's Issues

Module file was created by an older version of the compiler

I built this lib using carthage. My Cartfile looks like this:

github "auth0/JWTDecode.swift"

When I include import JWTDecode in my code, it shows the following error message:

Module file was created by an older version of the compiler; rebuild 'JWTDecode' and try again: /Users/elgs/Dev/iOS/LoginTest/Carthage/Build/iOS/JWTDecode.framework/Modules/JWTDecode.swiftmodule/x86_64.swiftmodule

M1 compatibility

Describe the problem you'd like to have solved

Compatibility for M1 macs.

Describe the ideal solution

Be able to compile on M1 macs for simulator.

Alternatives and current work-arounds

Run Xcode on Rosseta or run directly on the device.

Additional context

Could not find module 'JWTDecode' for target 'x86_64-apple-ios-simulator'; found: arm64, arm64-apple-ios-simulator, at: /Users/borutt/Library/Developer/Xcode/DerivedData/Proj-grnngzblfjxuwueukfcgqtmlzqbq/Build/Products/Dev_Debug-iphonesimulator/JWTDecode.swiftmodule

Using SPM.

Expiration date is not being parsed when the value comes as a string

Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJzdWIiOiJ4eHh4QHh4eHh4LmNvbSIsImlzcyI6Imh0dHBzOi8veHh4eHh4bnVtYmVycyIsImlhdCI6IjE0NTk4NzAyNzQiLCJleHAiOiIxNDU5ODcyMDc0IiwibmJmIjoiMTQ1OTg3MDI3NCIsImp0aSI6IjQ2ODA5YTYwNzQzMmU5ZDcwMmYwMWQ0MWQ2Y2FmMjNmIn0.fiA0lVKpUMkt48MGZ4J857V6hgDymJjtlx36oUm2W5s

["nbf": 1459870274, "exp": 1459872074, "iss": https://xxxxxx/numbers, "jti": 46809a607432e9d702f01d41d6caf23f, "iat": 1459870274, "sub": [email protected]]
nil


Sample Token:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL3NhbXBsZXMuYXV0aDAuY29tIiwic3ViIjoiYXV0aDB8MTAxMDEwMTAxMCIsImF1ZCI6Imh0dHBzOi8vc2FtcGxlcy5hdXRoMC5jb20iLCJleHAiOjEzNzI2NzQzMzYsImlhdCI6MTM3MjYzODMzNiwianRpIjoicXdlcnR5MTIzNDU2IiwibmJmIjoxMzcyNjM4MzM2fQ.LvF9wSheCB5xarpydmurWgi9NOZkdES5AbNb_UWk9Ew

["aud": https://samples.auth0.com, "sub": auth0|1010101010, "nbf": 1372638336, "iat": 1372638336, "jti": qwerty123456, "exp": 1372674336, "iss": https://samples.auth0.com]
Optional(2013-07-01 10:25:36 +0000)

Make Claim.value public

Right now Claim.value is not public. There is no direct way to pull out something like a Dictionary type directly. The simplest way would be to use .value and cast it, but it's not visible.

Use of unresolved identifier when archive

I am working in a project where cocopod is not integrated. I downloaded the JWTDecode project and added the JWTDecode.framework into our project. I got the JWTDecode.framework file when I run the sample project added JWTDecode project as cocoapod. So my project works well in simulator, I am able to decode the JWT token and get the claims. But when I trying to build/archive project it gives me an error Use of unresolved identifier 'decode'. Can you help me on this?

Check for invalid token?

Would it be possible to listen for jwt.invalid on Swift?

Maybe there is a better way but here is the problem I'm trying to solve:

In my Laravel (5.3) application I am trying to log the iOS user out.

Swift:
@IBAction func logout(_ sender: UIButton) {
print("hit logout")

    // need to call the token again
    let token: String! = KeychainWrapper.standard.string(forKey: "jwtoken")
    
    // create the header for the request
    let headers: HTTPHeaders = ["Authorization": "Bearer" + " " + token]
    
    // fire the get user data request
    Alamofire.request("https://mydomain.com", headers:headers).response in { 
           print("Logout - HTTP URL Response: \(response.response)")
    }

Laravel:
Maybe there is a better way someone can recommend?
public function logout() {
    $token = JWTAuth::getToken();
    JWTAuth::invalidate($token);
}

The error here returns {"error":"token_invalid"}
Would it be possible to listen for this with jwt.invalid ?

Failing to install via carthage

Getting this error when I do a carthage update:

The following build commands failed:
CompileSwift normal x86_64 /Carthage/Checkouts/JWTDecode.swift/JWTDecodeTests/JWTDecodeSpec.swift
CompileSwiftSources normal x86_64 com.apple.xcode.tools.swift.compiler
(2 failures)

Other projects in the Cartfile install just fine

Swift 5 support

In order to efficiently and accurately address your issue or feature request, please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. Please delete any sections or questions below that do not pertain to this request.

For general support or usage questions, please user the Auth0 Community.

Description

Description of the bug or feature request and why it's a problem. Consider including:

  • The use case or overall problem you're trying to solve
  • Information about when the problem started

Prerequisites

  • Did you check the documentation? [Add a link]
  • Did you check the Auth0 Community?
  • Are you reporting this to the correct repository?
  • Are there any related or duplicate Issues or PRs for this issue?

Environment

Please provide the following:

  • JWTDecode.swift version 2.2
  • iOS version 12.2
  • If using Carthage or CocoaPods: Cartfile
  • Xcode version 10.2

As Swift 5 is released with Xcode 10.2 is there any plans to update to Swift 5

Easy way to persist token

Right now, in order to persist the JWT, you have to persist the String that originated it, when you ideally, you could either:

1.- Obtain the JWT string that originated the JWT and persist that
2.- Add NSCoding compliance to the JTW protocol

I'm more inclined to option number 1, since that means keeping the JTW protocol purely Swift (no NSObjectProtocol cruft) and leaves completely to the caller how to persist the JTW

arm64 problem

Hello, I started to get this error:

Undefined symbols for architecture arm64:
  "(extension in JWTDecode):JWTDecode.JWT.claim (name : Swift.String) -> JWTDecode.Claim", referenced from:

I dont know why?

Handling milliseconds value comes in String

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Describe the problem

From the API now the sending now they are sending time with milliseconds in String format. While decoding its causes a crash. I get an error log like below

Could not cast value of type '__NSCFString' (0x25d9caf60) to 'NSNumber' (0x25d9d9588)

Provide a clear and concise description of the issue

My sample code form decode is were as follows, Could you please help me to resolve this? and let me know if anything I missed to handle.

public static func getTokenExp(basestring: String) -> NSInteger {
do {
let jwt = try decode(jwt: basestring)
return jwt.body["exp"] as! NSInteger
} catch let error as NSError {
print(error.localizedDescription)
return 0
}
}

What was the expected behavior?

Tell us about the behavior you expected to see

Reproduction

Detail the steps taken to reproduce this error, and whether this issue can be reproduced consistently or if it is intermittent.
Note: If clear, reproducible steps or the smallest sample app demonstrating misbehavior cannot be provided, we may not be able to follow up on this bug report.

  • Step 1..
  • Step 2..
  • ...

Where applicable, please include:

  • The smallest possible sample app that reproduces the undesirable behavior
  • Log information (redact/remove sensitive information)
  • Screenshots/GIFs

Environment

Please provide the following:

  • Version of JWTDecode.swift used:
  • Version of iOS/macOS/tvOS/watchOS:
  • Version of Xcode:

Expiry check should be time zone aware

First time working with JWT here, but looking at the expired check

    var expired: Bool {
        guard let date = self.expiresAt else {
            return false
        }
        return date.compare(Date()) != ComparisonResult.orderedDescending
    }

That check will be wrong anywhere except GMT, won't it? Shouldn't it convert Date() something like this?

    var expired: Bool {
        guard let date = self.expiresAt else {
            return false
        }
        return date.compare(Date().toUTC()) != ComparisonResult.orderedDescending
    }

extension Date {
    func toUTC() -> Date {
        let timezone = TimeZone.current
        let seconds = -TimeInterval(timezone.secondsFromGMT(for: self))
        return Date(timeInterval: seconds, since: self)
    }
}

JWTDecode fails to build with Swift 5.3 (Xcode 12)

Describe the problem

JWTDecode build fails in Xcode 12.0 GM (both from IDE and by using Command Line Tools)

What was the expected behavior?

JWTDecode build successful.

Reproduction

JWTDecode is mandatory dependency of Auth0.swift library. Issue was observed while trying to build Auth0.swift with Swift 5.3 compiler:

  1. Swifch to Xcode 12 Command Line tools.
  2. Checkout Auth0.swift
  3. Run carthage build --platform ios
  4. Observe JWTDecode build failure. There is no clear error in log file, it says ARCHIVE SUCCESSFUL and JWTDecode artefact created in Carthage/Build folder. 🤷‍♂️

Observations

  1. JWTDecode fails to build from Xcode 12 IDE:

Screenshot 2020-09-18 at 12 49 27

  1. JWTDecode builds successfully if Nimble version is updated to 9.0.0.rc.3 in Package.swift
dependencies: [
        // Dependencies declare other packages that this package depends on.
         .package(url: "https://github.com/Quick/Quick", from: "2.1.0"),
        .package(url: "https://github.com/Quick/Nimble", .revision("6956ffbde4ea6aab94fd2e823c5ede95072feef2"))
    ],

I have also tried switching Nimble to 9.0.0.rc.3 by updating Auth0.swift's Cartfile.resolved:

github "AliSoftware/OHHTTPStubs" "9.0.0"
github "Quick/Nimble" "6956ffbde4ea6aab94fd2e823c5ede95072feef2"
github "Quick/Quick" "v2.2.0"
github "auth0/JWTDecode.swift" "2.4.1"
github "auth0/SimpleKeychain" "0.11.1"

And I see that Carthage resolved Nimble version properly:
Screenshot 2020-09-18 at 12 13 56
However, build still fails with no clear error: carthage-xcodebuild.Elzx5t.log.zip

Environment

  • JWTDecode.swift v2.4.1
  • macOS 10.15.6
  • Xcode 12.0 GM (12A7209)

Swift 4 support

Support for Swift 4 / Xcode 9, which has a GM release as of 9/12

Next JWTDecode.swift major release

Hello! 👋

Today we published the JWTDecode.swift 3.0.0 First Availability release.

The GA release is planned for the third week of July.

Summary

  • Dropped support for Objective-C.
  • Dropped support for older platform and Swift versions.
  • Removed ID token validator.
  • Added a convenience subscript for accessing claims.
  • Improved the API documentation.

Documentation

Feedback

We’d love for you to give the FA release a try, and welcome your feedback on any recommendations or issues you encounter. Should you have any feedback or questions, please raise an issue.

Carthage fails

Hello,

I was trying to use JWTDecode in a swift project today. Unfortunately i'm having issue installing it using carthage.

using the following line in a newly create Cartfile file :

jdimarco@jdimarco-eth tmp $ mkdir test
jdimarco@jdimarco-eth tmp $ cd test/
jdimarco@jdimarco-eth test $ echo "github \"auth0/JWTDecode.swift\"" > Cartfile
jdimarco@jdimarco-eth test $ cat Cartfile 
github "auth0/JWTDecode.swift"
jdimarco@jdimarco-eth test $ carthage update
*** Fetching JWTDecode.swift
A shell task failed with exit code 128:
fatal: Refusing to fetch into current branch refs/heads/master of non-bare repository

jdimarco@jdimarco-eth test $ 

I don't really know what's the issue if it's carthage or this project configuration.

JWT validation

Hi!
Any plans to extend the library to support JWT validation in Swift as well?

Issue with time of expiration.

Hi,

I'm quite new to ios development.
I'm having a bit of trouble understanding how your isJWTExpired and expireDateOfJWT works.

My token looks like this:

eyJhbGciOiJIUzI1NiIsImV4cCI6MTQyNzQ2OTA4NSwiaWF0IjoxNDI3NDY4Nzg1fQ.eyJ1c2VyX2lkIjo0LCJuYmYiOjE0Mjc0ODY3ODIuMCwiZXhwIjoxNDI3NDg3MDgyLjB9.X1o75sv3-Iq4mk3gmHYysnkOS-CfRi4dOQ97fOq3I10

From what your code is saying, it is taking the exp from the claims section correct? So that should be 1427487082

var exp2 = NSDate(timeIntervalSince1970:1427487082.doubleValue)

When running the code through swift playground I'm getting "Mar 27, 2015, 3:11 PM" <<< UTC time.., which I believe is correct. But when I use your expiryDate method it returns back 2015-03-27 20:11:22 +0000.

I'm a bit puzzled as to why this is happening. Is it me sending the incorrect time?

Thanks :)

Support for Swift 2.1

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

Minimum iOS version for 2.1.1?

The README page mentions iOS 9+ is required, but the Podspec specifies iOS 8.0.0 -- so 2.1.1 will be installed on a project with deployment target less than 9.

Which one is true?

Pod is not Swift 3 compliant

This pod is not compiling for me using swift 3. Its noting a tremendous number of swift 3 errors. Notably lots of public to open declarations on extendable class methods.

Is anyone else having this issue?

Support Swift package manager for server side Swift apps

I am working on a server side Swift project with Vapor and would like to use Auth0 but I am finding that there is a lack of support for native Swift packages that can run on Linux. This seems like it could be a great starting point to add support for server side Swift to Auth0 since this doesn't seems to need UIKit

Swift 2.3 support

I'll be crating a pull request soon with the necessary changes to make this lib to support Xcode 8 and Swift 2.3. The changes do not affect Xcode 7 and Swift 2.2

Converting Payload to custom object

Hi i have payload in following format:

{
  "Person": {
    "PersonGuid": [
      "e38cf4eb-6509-4ed9-933d-9b5ad111116b"
    ]
  },
  "TokenEndLifeTime": "2017-09-28T18:45:46.7964642+03:00"
}

and class for that:

class Person {
    var PersonGuid: [String]?
}

i getting nil in this lines for person variable:

let jwt = try decode(jwt: data.Token!)
let person = jwt.body["Person"] as? Person

Thank you in advance!

Expiry date is nil

Hi,

After decoding any JWT token, I would always get a nil value for expiresAt and false for expired. I managed to make it work by changing two lines of code.

// JWTDecode.swift

// Lines 67 - 72
private func claim(name: String) -> NSDate? {
    guard let timestamp:Double = Double(claim(name)!) else { // <-- wrapped claim() in Double()
        return nil
    }
    return NSDate(timeIntervalSince1970: timestamp)
}

// Lines 74 - 78
var expired: Bool {
    guard let date = self.expiresAt else {
        return false
    }
    return date.timeIntervalSinceNow.isSignMinus // <-- check if the time interval to now is negative
}

I am unsure whether or not I am doing something wrong in the decoding process, but my code looks something like:

import JWTDecode

// ...

let jwt = try decode(token)

if jwt.expired {
    // refresh token
}

Cheers.

Claims value nil, but payload seems fine

I can print out my idToken, cut and paste it into https://jwt.io and I see all my payload data, but when I try to use JWTDecode I'm getting all nil values for my claims.

        do {
            let jwt = try decode(jwt: idToken)

            let lastNameClaim = jwt.claim(name: "lastName")
            if let lastName = lastNameClaim.string {
                print("Last name in jwt was \(lastName)")
            }

            let claim = jwt.claim(name: "userID")
            if let email = claim.string {
                print("Email in jwt was \(email)")
            }
        } catch {
            print("JWT fail: \(error.localizedDescription)")
        }

Nothing prints and I stick a breakpoint into the debugger I see the claim.value is nil. Looking at jwt.body shows my custom attributes in custom_attributes Dictionary as expected. Here is an example ID token (signature removed for smaller sizing)

eyJraWQiOiIyMTIiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoicVpxOXRLN0dWME81ZFZnQWtGSVpYdyIsInN1YiI6Imh0dHBzOi8vdGVzdC5zYWxlc2ZvcmNlLmNvbS9pZC8wMEQyNTAwMDAwMERxU2NFQUsvMDA1MjUwMDAwMDJ1M29vQUFBIiwiYXVkIjoiM01WRzlyS2hUOG9jb3hHazFFbkZLVGZ2TXZjRV9xQy5hMEQ5S0VpR2VOQmJiaHRHd2h1c2VfWjRENlAuN1pfRnVWMEFjWFRfakhYeVFDc2lOOUk0aCIsImlzcyI6Imh0dHBzOi8vdGVzdC1tdGwuY3M4MC5mb3JjZS5jb20vIiwiZXhwIjoxNTIzNTUyMDYxLCJpYXQiOjE1MjM1NTE5NDEsImN1c3RvbV9hdHRyaWJ1dGVzIjp7Imxhc3ROYW1lIjoiTWFjayIsImZpcnN0TmFtZSI6IkRhdmlkIiwiZmVkZXJhdGlvbklEIjoiRkVELTAwMTM3NzU4NDIiLCJ1c2VySUQiOiJkYXZpZC5tYWNrQHRldmFwaGFybS5jb20ifX0

Any help appreciated.

Swift 3 Support

Would be great for testing if this library could be updated to support swift 3.

Version missing in JWT podscpec 2.4.0 on Github

Please do not report security vulnerabilities here. The Responsible Disclosure Program details the procedure for disclosing security issues.

Thank you in advance for helping us to improve this library! Please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. For general support or usage questions, use the Auth0 Community or Auth0 Support. Finally, to avoid duplicates, please search existing Issues before submitting one here.

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

In the following podspec

https://github.com/auth0/JWTDecode.swift/blob/2.4.0/JWTDecode.podspec

the version is missing. As I need it for internal referencing purposes - could you please add the corresponding version into the Podspec?

Reproduction

podspec

Environment

Please provide the following:

  • Version of this library used: 2.4.0
  • Version of the platform or framework used, if applicable:
  • Other relevant versions (language, server software, OS, browser):
  • Other modules/plugins/libraries that might be involved:

Swift Package Manger support?

In order to efficiently and accurately address your issue or feature request, please read through the template below and answer all relevant questions. Your additional work here is greatly appreciated and will help us respond as quickly as possible. Please delete any sections or questions below that do not pertain to this request.

For general support or usage questions, please user the Auth0 Community.

Description

XCode11 comes with native support for SPM for all project types. This will quickly become the preferred way to manage dependencies. JWTDecode could easily support SPM as it exists today and require no changes when XCode11 goes live to support its usage of SPM.

Prerequisites

  • Did you check the documentation? [Add a link]
  • Did you check the Auth0 Community?
  • Are you reporting this to the correct repository?
  • Are there any related or duplicate Issues or PRs for this issue?

Environment

Please provide the following:

  • JWTDecode.swift version 2.2.0
  • iOS version 12.2
  • If using Carthage or CocoaPods, please include your Cartfile or Podfile N/A
  • Xcode version 10.2

Reproduction

Invalid id_token claims part. Failed to decode base64

Some JTW payloads could not be decoded and failed with this error.

This occurred in payloads which included an url. (not all url's failed)
I was able to fix this with this lib:https://github.com/qmihara/QMBase64URLSafe

and replacing:
NSData *claimsData = [[NSData alloc] initWithBase64EncodedString:claimsBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];

with:
NSData *claimsData = [[NSData alloc] qm_initWithBase64URLSafeEncodedString:claimsBase64 options:NSDataBase64DecodingIgnoreUnknownCharacters];

Support for timestamp expiration date with milliseconds ( 13 digits)

The computed property "expired" in the class JWT, only works when the number of timestamp expiration digits are 10. Sometimes the backend generates a timestamp with 13 digits (including milliseconds), and this property is always returns false.

Example
let jsonWebToken = try decode(jwtWithUnixExp: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1ODE3MjMwMzIwMDB9.Ku_xrqNKYgNRvqGvs4hc7TVpbO9pS3vn2wv95f8N2f4")
print(jsonWebToken.expired)

Would be great have a init method for timestamp expiration with 13 digits (Include miliseconds ). I think that maybe its a bit tricky, however I have not idea for another solution.

Example
let jsonWebToken = try decode(jwtWithUnixExp: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1ODE3MjMwMzIwMDB9.Ku_xrqNKYgNRvqGvs4hc7TVpbO9pS3vn2wv95f8N2f4")
print(jsonWebToken.expired)

I created a local branch with a proposed solution, however I can not do push and pull request. I hope let me try it.

Your Pod its amazing. Congratulations. Its too util for me.

Error when using Swift 2.1 at line 108 in JWTDecode.swift

Error when using Swift 2.1 at line 108 in JWTDecode.swift

    public func payloadWithError(error: NSErrorPointer) -> [String: AnyObject]? {
        let parts = jwt.componentsSeparatedByString(".")
        if parts.count != 3 {
            if error != nil {
                error.memory = errorWithDescription(NSLocalizedString("malformed jwt token \(jwt) only has \(parts.count) parts (3 parts are required)", comment: "Not enough jwt parts"))
            }
            return nil
        }
        var base64 = parts[1]
            .stringByReplacingOccurrencesOfString("-", withString: "+")
            .stringByReplacingOccurrencesOfString("_", withString: "/")
        let length = Double(base64.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
        let requiredLength = 4 * ceil(length / 4.0)
        let paddingLength = requiredLength - length
        if paddingLength > 0 {
            let padding = "".stringByPaddingToLength(Int(paddingLength), withString: "=", startingAtIndex: 0)
            base64 = base64.stringByAppendingString(padding)
        }
        if let data = NSData(base64EncodedString: base64, options: .IgnoreUnknownCharacters) {
          return NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: error) as? [String: AnyObject]
        } else {
            if error != nil {
                error.memory = errorWithDescription(NSLocalizedString("malformed jwt token \(jwt). failed to decode base64 payload", comment: "Invalid base64"))
            }
        }
        return nil
    }

For the parameter options: in return NSJSONSerialization.JSONObjectWithData(data, options: .allZeros, error: error) as? [String: AnyObject] there is no argument: .allZeros

Test target dependencies failed to install via SSH

By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.

Description

Screenshot 2020-04-23 at 14 14 17

Test target dependencies not installing if SSH used. Receiving Authentication failed because no credentials were provided. Might be Xcode issue, but probably anybody else had this.

Reproduction

Add Swift Package Manager dependency via ssh: [email protected]:auth0/JWTDecode.swift.git

Environment

  • JWTDecode.swift version 2.4.1
  • Xcode 11.4.1

Swift 2.x

Which previous version do you recommend for those who are immediately moving to Swift 3.0?

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.