Last active
March 30, 2020 18:42
-
-
Save arbel03/4b880f8eab7d7dbe4242ae96a63d6f8d to your computer and use it in GitHub Desktop.
Swift extension of a URLRequest that add Basic Authentication to the authorization header of a HTTP request as per rfc7617: https://tools.ietf.org/html/rfc7617
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// BasicAuthenticationExtension.swift | |
// ToCheckIn | |
// | |
// Created by arbel03 on 25/08/2016. | |
// Copyright © 2016 arbel03. All rights reserved. | |
// | |
import Foundation | |
extension NSMutableURLRequest { | |
//Adding base64 encoded authorization field | |
func addBasicAuthentication(username username: String, password: String) { | |
let utf8String = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) | |
if let base64Encoded = utf8String?.base64EncodedDataWithOptions(NSDataBase64EncodingOptions(rawValue: 0)) { | |
self.setValue("Basic \(NSString(data: base64Encoded, encoding: NSUTF8StringEncoding)!)", forHTTPHeaderField: "Authorization") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment