How can I decode JWT (JSON web token) token in Swift?
I have got the solution for this.
static func getJwtBodyString(tokenstr: String) -> NSString {
var segments = tokenstr.components(separatedBy: ".")
var base64String = segments[1]
print("\(base64String)")
let requiredLength = Int(4 * ceil(Float(base64String.characters.count) / 4.0))
let nbrPaddings = requiredLength - base64String.characters.count
if nbrPaddings > 0 {
let padding = String().padding(toLength: nbrPaddings, withPad: "=", startingAt: 0)
base64String = base64String.appending(padding)
}
base64String = base64String.replacingOccurrences(of: "-", with: "+")
base64String = base64String.replacingOccurrences(of: "_", with: "/")
let decodedData = Data(base64Encoded: base64String, options: Data.Base64DecodingOptions(rawValue: UInt(0)))
// var decodedString : String = String(decodedData : nsdata as Data, encoding: String.Encoding.utf8)
let base64Decoded: String = String(data: decodedData! as Data, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
print("\(base64Decoded)")
return base64String as NSString
}
This works for me great. Thank you.
Decoding JSON Web Tokens in Swift
eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0
is not a valid Base64 encoded string because its length
is not a multiple of 4. Some Base64 decoder tolerate this error, but
the NSData
methods don't.
So this is actually an error on the server side creating the
Base64 encoded string. If necessary, you can fix it in your app
by adding the required padding with =
characters (code updated for Swift 2):
var base64String = arr[1] as String
if base64String.characters.count % 4 != 0 {
let padlen = 4 - base64String.characters.count % 4
base64String += String(count: padlen, repeatedValue: Character("="))
}
And now the decoding works as expected:
if let data = NSData(base64EncodedString: base64String, options: []),
let str = String(data: data, encoding: NSUTF8StringEncoding) {
print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}
}
Swift 4:
var base64String = "eyJleHAiOjE0MjY4MjIxNjMsImlkIjoiNTUwYjA3NzM4ODk1NjAwZTk5MDAwMDAxIn0"
if base64String.count % 4 != 0 {
let padlen = 4 - base64String.count % 4
base64String.append(contentsOf: repeatElement("=", count: padlen))
}
if let data = Data(base64Encoded: base64String) ,
let str = String(data: data, encoding: .utf8) {
print(str) // {"exp":1426822163,"id":"550b07738895600e99000001"}
}
How do I decode JSON(JSON Web Token) in Swift 4?
Works like this:
struct User : Codable
{ var id : String
}
struct JWT : Codable
{ var success : Bool
var token : String
var user :User
}
let json = """
{ \"success\" : true,
\"token\" : \"***\",
\"user\":
{ \"id\": \"59f0ec6d5479390345980cc8\",
\"username\": \"john\",
\"email\": \"john@gmail.com\"
}
}
"""
let decoder = JSONDecoder()
let jwt = try decoder.decode(JWT.self, from: json.data(using: .utf8)!)
print ("token: \(jwt.token)")
JWT Token Decode SwiftUI
You should return back JWTData
instance populated with decoded result. In below code I am directly returning initialised object, you have to first decode as you are already doing, and populate the values.
import SwiftUI
protocol Token {
func getJwtToken() -> JWTData
var jwtString:String{get set}
}
class TokenDecoder : Token {
var jwtString: String = "myToken"
var jwtObj:JWTData?
func getJwtToken() -> JWTData{
// Perform JWTdecoding and return object
JWTData(first_name:"foo",last_name:"bar",email:"abc@xyz.com",user_verified:false)
}
}
class MyJWTClaims : ObservableObject {
@Published var data : JWTData?
init(decoder:Token) {
self.data = decoder.getJwtToken()
}
}
struct JWTData:Decodable {
var first_name : String?
var last_name : String?
var email : String?
var user_verified : Bool?
}
struct ProfileTopView : View {
@ObservedObject var jwtTokenData = MyJWTClaims(decoder: TokenDecoder())
var body: some View {
ZStack{
Image("CDF")
.resizable()
.frame(width: UIScreen.main.bounds.width * 1, height: UIScreen.main.bounds.height * 0.15, alignment: .center)
Image("Home")
.resizable()
.frame(width: UIScreen.main.bounds.width * 0.22, height: UIScreen.main.bounds.height * 0.10, alignment: .center)
.offset(x: 0, y: UIScreen.main.bounds.height * 0.048)
Text(jwtTokenData.data?.first_name ?? "Test")
.font(.system(size: 14))
.bold()
.offset(x: 0, y: UIScreen.main.bounds.height * 0.14)
}.ignoresSafeArea(.all)
}
}
How to logout and destory token in PyJWT Django?
So i found the solution. JWT tokens are not destroyable. And best way for us to do is make a table in our database like blacklist and add dead tokens ito it when call logout method.
And then when try to check user token validation just check that table and if the token exist, you should not accept user and return User Not Authenticated
.
Be successful
Related Topics
How to Calculate Uilabel Width Based on Text Length
iOS Keeping Old Launch Screen and App Icon After Update
Uitableview Row Animation Duration and Completion Callback
Where's the Difference Between Setobject:Forkey: and Setvalue:Forkey: in Nsmutabledictionary
Developing for iOS Device in Windows Environment with Flutter
How to Remove the Default Navigation Bar Space in Swiftui Navigationview
Rsa Implementations in Objective C
Detect First Launch of iOS App
How to Change Locale Programmatically with Swift
iOS - Calling App Delegate Method from Viewcontroller
Autolayout with Hidden Uiviews
iOS 11 Navigation Bar Height Customizing
Long Press Gesture on Uicollectionviewcell
Swift - Problems with Corner Radius and Drop Shadow