0001    //
0002    //  BasicAuth.swift
0003    //  HttpBasicAuth
0004    //
0005    //  This source file is part of the HttpBasicAuth open source project
0006    //
0007    //  Created by John Becker on 1/13/16.
0008    //  Copyright © 2016 Beckersoft. All rights reserved.
0009    //  Licensed under MIT License
0010    //
0011    //  See LICENSE.txt for license information.
0012    //
0013    
0014    /**
0015    A library for parsing Basic HTTP Authentication credentials from a header
0016    dictionary.
0017    */
0018    public class BasicAuth {
0019        
0020        /**
0021         Regular Expression for basic auth credentials
0022         
0023         credentials = auth-scheme 1*SP token68
0024         auth-scheme = "Basic" ; case insensitive
0025         token68     = 1*( ALPHA / DIGIT / "-" / "." / "_" / "~" / "+" / "/" ) *"="
0026         */
0027        internal static let credentialsRegEx
BasicAuth.swift:51
            encodedAuth = header.regexMatches(credentialsRegEx).last,
= 0028 "^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9\\-\\._~\\+\\/]+=*) *$" 0029 0030 /** 0031 Regular Expression for basic auth user/pass 0032 0033 user-pass = userid ":" password 0034 userid = *<TEXT excluding ":"> 0035 password = *TEXT 0036 */ 0037 internal static let userPassRegEx
BasicAuth.swift:55
            let userPass = decodedAuth.regexMatches(userPassRegEx)
= "^([^:]*):(.*)$" 0038 0039 /** 0040 Parse the Authorization header field of a request. 0041 0042 - Parameter headers: A dictionary of HTTP headers. 0043 0044 - Returns: Credentials with the username and password or nil if none exist. 0045 */ 0046 public class func getCredentials(headers:[String:String]) -> Credentials? { 0047 0048 // get header 0049 if let header = headers["Authorization"], 0050 // regex match the base64 encoded basic authorization 0051 encodedAuth = header.regexMatches(credentialsRegEx).last, 0052 // base64 decode the auth string 0053 decodedAuth = encodedAuth.base64Decode() { 0054 // regex match the username and password 0055 let userPass = decodedAuth.regexMatches(userPassRegEx) 0056 // ensure we have enough matches 0057 if userPass.count == 3 { 0058 // return the Credentials with the username and password 0059 return Credentials(username:userPass[1], password:userPass[2]) 0060 } 0061 } 0062 0063 // no credentials were found 0064 return nil 0065 } 0066 0067 } 0068 0069