auth0 / jwtdecode.swift Goto Github PK
View Code? Open in Web Editor NEWA JWT decoder for iOS, macOS, tvOS, and watchOS
Home Page: https://auth0.github.io/JWTDecode.swift
License: MIT License
A JWT decoder for iOS, macOS, tvOS, and watchOS
Home Page: https://auth0.github.io/JWTDecode.swift
License: MIT License
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 ?
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?
By submitting an Issue to this repository, you agree to the terms within the Auth0 Code of Conduct.
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.
Add Swift Package Manager dependency via ssh: [email protected]:auth0/JWTDecode.swift.git
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.
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?
Would be great for testing if this library could be updated to support swift 3.
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];
Why do we to try?
let jwt = try decode(jwt: token)
On Release tag 1.0.0 the prebuilt framework for Carthage is out of date. Looks as if it was compiled for a previous Swift version.
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
SwiftPM uses tags conforming to semver to determine release builds. The 9.9.9 tag breaks this scheme, can you please delete it?
When I build, I'm getting an error that JWTDecode targets 8.3. Thanks!
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
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)
Hi ,
is there any pod version that support "target 8.0 and swift 3"
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.
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.
Please provide the following:
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?
When I put this line let jwt = try decode(token)
in my code, it doesn't compile. Is it valid Swift code?
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?
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
Hi, please consider adding support for watchOS in the cocoapod.
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.
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?
Please provide the following:
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.
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
The Releases link in the README (https://github.com/auth0/JWTDecode.swift/blob/master/releases) returns a 404.
Hi!
Any plans to extend the library to support JWT validation in Swift as well?
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 :)
Errors.swift
Identifier Name Violation: Enum element name should only contain alphanumeric characters: 'invalidBase64Url(_:)' (identifier_name)
Support for Swift 4 / Xcode 9, which has a GM release as of 9/12
Can the "Require Only App-Extension-Safe API" flag be enabled to stop the warning "linking against dylib not safe for use in application extensions" when referencing JWTDecode framework in an extension.
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!
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.
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.
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.
Hi ,
can you please provide version of lib that support swift 2.1 ? It would be of G8 help !
Hello! ๐
Today we published the JWTDecode.swift 3.0.0 First Availability release.
The GA release is planned for the third week of July.
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.
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
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 of the bug or feature request and why it's a problem. Consider including:
Please provide the following:
As Swift 5 is released with Xcode 10.2 is there any plans to update to Swift 5
JWTDecode
build fails in Xcode 12.0 GM (both from IDE and by using Command Line Tools)
JWTDecode
build successful.
JWTDecode
is mandatory dependency of Auth0.swift
library. Issue was observed while trying to build Auth0.swift
with Swift 5.3 compiler:
Auth0.swift
carthage build --platform ios
JWTDecode
build failure. There is no clear error in log file, it says ARCHIVE SUCCESSFUL
and JWTDecode
artefact created in Carthage/Build
folder. ๐คทโโ๏ธJWTDecode
fails to build from Xcode 12 IDE: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:
However, build still fails with no clear error: carthage-xcodebuild.Elzx5t.log.zip
JWTDecode.swift v2.4.1
macOS 10.15.6
Xcode 12.0 GM (12A7209)
Should be able use String or Substring directly
Thanks,
Mehdi
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)
}
}
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.
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
}
}
Tell us about the behavior you expected to see
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.
Where applicable, please include:
- The smallest possible sample app that reproduces the undesirable behavior
- Log information (redact/remove sensitive information)
- Screenshots/GIFs
Please provide the following:
JWTDecode.swift
used:Which previous version do you recommend for those who are immediately moving to Swift 3.0?
Is it possible to validate the signature of the JWT using my RSA public key on the device?
RSA(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret
https://github.com/AndrewSB/Expirable
This github has a great way for detecting if a JWT is soon to be expired as well as expiresAt.
Was wondering if it was able to be subclassed
Compatibility for M1 macs.
Be able to compile on M1 macs for simulator.
Run Xcode on Rosseta or run directly on the device.
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.
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
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.