Skip to content

Instantly share code, notes, and snippets.

@arbel03
Last active March 30, 2020 18:42
Show Gist options
  • Save arbel03/4b880f8eab7d7dbe4242ae96a63d6f8d to your computer and use it in GitHub Desktop.
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
//
// 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