Swift에서 JWT(JSON Web 토큰) 토큰을 디코딩하려면 어떻게 해야 하나요?
이런 JWT 토큰이 있어요.
eyJhbGciOiJIUZI1NiIsInR5cCI6IkpXVCJ9.eyJzdWiiOiIxMjM0NTY3ODkwIwibmFtZSI6IkpvaG4gRG9lIiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFonFH7HgQ
어떻게 해독하면 이렇게 페이로드를 얻을 수 있을까요?
{ "sub": "1234567890", "name": "John Doe", "admin": true}
도서관을 이용해도 괜찮으시다면 https://github.com/auth0/JWTDecode.swift을 추천합니다.
다음으로 라이브러리를 Import합니다.import JWTDecode
를 실행합니다.
let jwt = try decode(jwt: token)
당신이 이 라이브러리를 포함시키고 싶지 않았기 때문에, 저는 그것을 작동시키기 위해 필요한 부품을 가지고 왔습니다.
func decode(jwtToken jwt: String) -> [String: Any] {
let segments = jwt.components(separatedBy: ".")
return decodeJWTPart(segments[1]) ?? [:]
}
func base64UrlDecode(_ value: String) -> Data? {
var base64 = value
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8))
let requiredLength = 4 * ceil(length / 4.0)
let paddingLength = requiredLength - length
if paddingLength > 0 {
let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0)
base64 = base64 + padding
}
return Data(base64Encoded: base64, options: .ignoreUnknownCharacters)
}
func decodeJWTPart(_ value: String) -> [String: Any]? {
guard let bodyData = base64UrlDecode(value),
let json = try? JSONSerialization.jsonObject(with: bodyData, options: []), let payload = json as? [String: Any] else {
return nil
}
return payload
}
이렇게 불러주세요.
decode(jwtToken: TOKEN)
Viktor 코드 반복:
- 네스트된 함수를 사용하여 모듈러형 유지
- 잘못된 토큰이 통과되거나 다른 오류가 발생한 경우 예외를 사용합니다.
- 패딩 계산 및 패딩 함수 활용을 단순화합니다.
도움이 되길 바랍니다.
func decode(jwtToken jwt: String) throws -> [String: Any] {
enum DecodeErrors: Error {
case badToken
case other
}
func base64Decode(_ base64: String) throws -> Data {
let base64 = base64
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let padded = base64.padding(toLength: ((base64.count + 3) / 4) * 4, withPad: "=", startingAt: 0)
guard let decoded = Data(base64Encoded: padded) else {
throw DecodeErrors.badToken
}
return decoded
}
func decodeJWTPart(_ value: String) throws -> [String: Any] {
let bodyData = try base64Decode(value)
let json = try JSONSerialization.jsonObject(with: bodyData, options: [])
guard let payload = json as? [String: Any] else {
throw DecodeErrors.other
}
return payload
}
let segments = jwt.components(separatedBy: ".")
return try decodeJWTPart(segments[1])
}
func decode(_ token: String) -> [String: AnyObject]? {
let string = token.components(separatedBy: ".")
let toDecode = string[1] as String
var stringtoDecode: String = toDecode.replacingOccurrences(of: "-", with: "+") // 62nd char of encoding
stringtoDecode = stringtoDecode.replacingOccurrences(of: "_", with: "/") // 63rd char of encoding
switch (stringtoDecode.utf16.count % 4) {
case 2: stringtoDecode = "\(stringtoDecode)=="
case 3: stringtoDecode = "\(stringtoDecode)="
default: // nothing to do stringtoDecode can stay the same
print("")
}
let dataToDecode = Data(base64Encoded: stringtoDecode, options: [])
let base64DecodedString = NSString(data: dataToDecode!, encoding: String.Encoding.utf8.rawValue)
var values: [String: AnyObject]?
if let string = base64DecodedString {
if let data = string.data(using: String.Encoding.utf8.rawValue, allowLossyConversion: true) {
values = try! JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as? [String : AnyObject]
}
}
return values
}
이 문제에 대한 해결책이 있어
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
}
이건 나한테 아주 잘 먹힌다.감사해요.
신속한 이행이 있습니다.코코아팟을 사용하거나 프로젝트를 복제한 후 직접 사용할 경우 이 파일을 포드 파일에 추가하십시오.
do {
// the token that will be decoded
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
let payload = try JWT.decode(token, algorithm: .hs256("secret".data(using: .utf8)!))
print(payload)
} catch {
print("Failed to decode JWT: \(error)")
}
도서관을 이용하고 싶다고 생각하고 있습니다만, 큰 사람의 인기 있는 것을 추천하고 있습니다.IBM은 Kitura – Swift 백엔드 프레임워크를 만들고 있으므로 이를 위한 JWT 인코딩 및 디코딩은 최고 수준이어야 합니다.
링크: https://github.com/IBM-Swift/Swift-JWT
만료 날짜가 있는 토큰의 간단한 사용
import SwiftJWT
struct Token: Decodable {
let jwtString: String
func abc() {
do {
let newJWT = try JWT<MyJWTClaims>(jwtString: jwtString)
print(newJWT.claims.exp)
} catch {
print("OH NOES")
}
}
}
struct MyJWTClaims: Claims {
let exp: Date
}
Oldies용 Objective-C 버전:
NSLog(@"credential is %@", credential.identityToken);
NSString * string = [[NSString alloc] initWithData:credential.identityToken encoding:NSUTF8StringEncoding];
NSArray * segments = [string componentsSeparatedByString:@"."];
NSMutableDictionary * JSON = [NSMutableDictionary new];
for (int n = 0; n < segments.count; n++){
NSString * value = segments[n];
NSString * base64 = [value stringByReplacingOccurrencesOfString:@"-" withString:@"+"];
base64 = [base64 stringByReplacingOccurrencesOfString:@"_" withString:@"/"];
NSUInteger length = [base64 lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
int requiredLength = 4 * ceil((float)length/4.0f);
int paddingLength = requiredLength - (int)length;
for (int n = 0; n < paddingLength; n++){
base64 = [base64 stringByAppendingString:@"="];
}
NSData * data = [[NSData alloc] initWithBase64EncodedString:base64 options:0];
NSError * error;
NSDictionary * local = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:&error];
[JSON addEntriesFromDictionary:local];
}
NSLog(@"JSON is %@", JSON);
@Viktor Gardart 코드를 리팩터링했습니다.
이렇게 쓰세요.
let token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhY2NvdW56IiwianRpIjoiZTA0NGEyMTAtZjVmZi00Yjc2LWI2MzMtNTk0NjYzMWE0MjRjLWQxYTc3bXlpdGE0YnZnaG4yd2YiLCJleHAiOjE2NDk2NDI3MTF9.FO-AQhZ18qogsSbeTUY78EqhfL9xp9iUG3OlpOdxemE"
let jsonWebToken = JSONWebToken(jsonWebToken: token)
let expirationTime = jsonWebToken?.payload.expirationTime
JSON Web Token.swift
import Foundation
struct JSONWebToken {
let header: JSONWebTokenHeader
let payload: JSONWebTokenPayload
let signature: String
}
extension JSONWebToken {
init?(jsonWebToken: String) {
let encodedData = { (string: String) -> Data? in
var encodedString = string.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
switch (encodedString.utf16.count % 4) {
case 2: encodedString = "\(encodedString)=="
case 3: encodedString = "\(encodedString)="
default: break
}
return Data(base64Encoded: encodedString)
}
let components = jsonWebToken.components(separatedBy: ".")
guard components.count == 3,
let headerData = encodedData(components[0] as String),
let payloadData = encodedData(components[1] as String) else { return nil }
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
header = try decoder.decode(JSONWebTokenHeader.self, from: headerData)
payload = try decoder.decode(JSONWebTokenPayload.self, from: payloadData)
signature = components[2] as String
} catch {
print(error.localizedDescription)
return nil
}
}
}
JSON Web Token Header.swift
import Foundation
struct JSONWebTokenHeader {
let type: String
let algorithm: String
}
extension JSONWebTokenHeader: Codable {
private enum Key: String, CodingKey {
case type = "typ"
case algorithm = "alg"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
do { try container.encode(type, forKey: .type) } catch { throw error }
do { try container.encode(algorithm, forKey: .algorithm) } catch { throw error }
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
do { type = try container.decode(String.self, forKey: .type) } catch { throw error }
do { algorithm = try container.decode(String.self, forKey: .algorithm) } catch { throw error }
}
}
JSON Web Token Payload.swift
import Foundation
struct JSONWebTokenPayload {
let issuer: String
let expirationTime: Double
let jsonWebTokenID: String
}
extension JSONWebTokenPayload: Codable {
private enum Key: String, CodingKey {
case issuer = "iss"
case expirationTime = "exp"
case jsonWebTokenID = "jti"
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: Key.self)
do { try container.encode(issuer, forKey: .issuer) } catch { throw error }
do { try container.encode(expirationTime, forKey: .expirationTime) } catch { throw error }
do { try container.encode(jsonWebTokenID, forKey: .jsonWebTokenID) } catch { throw error }
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Key.self)
do { issuer = try container.decode(String.self, forKey: .issuer) } catch { throw error }
do { expirationTime = try container.decode(Double.self, forKey: .expirationTime) } catch { throw error }
do { jsonWebTokenID = try container.decode(String.self, forKey: .jsonWebTokenID) } catch { throw error }
}
}
언급URL : https://stackoverflow.com/questions/40915607/how-can-i-decode-jwt-json-web-token-token-in-swift
'programing' 카테고리의 다른 글
XMLHttpRequest, jQuery.ajax, jQuery.post, jQuery.get의 차이점은 무엇입니까? (0) | 2023.03.26 |
---|---|
스프링 부트 테스트가 실패하고 "Servlet Web Server Factory bean이 없어 Servlet Web Server Application Context를 시작할 수 없습니다. (0) | 2023.03.26 |
WooCommerce:가격을 무시하고 제품을 장바구니에 추가하시겠습니까? (0) | 2023.03.26 |
config()에 $location을 삽입할 수 없는 이유는 무엇입니까? (0) | 2023.03.26 |
ToString 메서드에 대한 오버로드가 없습니다.일자를 캐스팅할 때 1개의 인수를 사용합니다. (0) | 2023.03.26 |