How to make HTTP post request with specific body? And how to access token from the server to allow me to login? - authentication

I'm having a scenario like :
1) I want to create Http POST request and for this I'm having the data, please see this image:
2) As you can see in the above image, I have to create post a request with the mentioned body and also I'm getting response named: token. How to create post request and fetch this token response?.
3) That token response will allow me to login into myapp.
I'm newbie to this scenario. I have tried some code by my own but still getting confuse in how to combine my app delegate code with this POST Request Code.
Code
#IBAction func signinaction(_ sender: Any) {
self.username.resignFirstResponder()
self.password.resignFirstResponder()
if (self.username.text == "" || self.password.text == "") {
let alertView = UIAlertController(title: "Login failed",
message: "Wrong username or password." as String, preferredStyle:.alert)
let okAction = UIAlertAction(title: "Try Again!", style: .default, handler: nil)
alertView.addAction(okAction)
self.present(alertView, animated: true, completion: nil)
return
}
// Check if the user entered an email
if let actualUsername = self.username.text {
// Check if the user entered a password
if let actualPassword = self.password.text {
// Build the body message to request the token to the web app
self.bodyStr = "username=8870417698&password=1234&grant_type=password" + actualUsername + "&password=" + actualPassword
// Setup the request
let myURL = NSURL(string: "http://ezschoolportalapi.azurewebsites.net/token")!
let request = NSMutableURLRequest(url: myURL as URL)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = bodyStr.data(using: String.Encoding.utf8)!
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if data?.count != 0
{
do {
let tokenDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
print(tokenDictionary)
// Get the token
let token:String = tokenDictionary["access_token"] as! String
// Keep record of the token
let userdefaults = UserDefaults()
let saveToken = userdefaults.set(token, forKey: "access_token")
userdefaults.synchronize()
// Dismiss login view and go to the home view controller
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
catch {
// Wrong credentials
// Reset the text fields
self.username.text = ""
self.password.text = ""
// Setup the alert
let alertView = UIAlertController(title: "Login failed",
message: "Wrong username or password." as String, preferredStyle:.alert)
let okAction = UIAlertAction(title: "Try Again!", style:.default, handler: nil)
alertView.addAction(okAction)
self.present(alertView, animated: true, completion: nil)
return
}
}
}
task.resume()
}
}
}
Question is how to combine this code with my above code :
let appDelegate = UIApplication.shared.delegate as! AppDelegate appDelegate.gotoMainvc()
if I use directly this code then in any of the case I'm able to switch over to my home screen it doesn't matter whether m using this POST Request code or not. Please Help.

You are hard coding the username and password in bodyStr update it to
self.bodyStr = "username=" + actualUsername + "&password=" + actualPassword + "&grant_type=password"
Update the statements inside do with
do {
let tokenDictionary:NSDictionary = try JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! NSDictionary
print(tokenDictionary)
// Get the token
if let authToken = tokenDictionary["access_token"] as? String{
self.token = authToken
UserDefaults.standard.set(accessToken, forKey: "access_token")
UserDefaults.standard.synchronize()
DispatchQueue.main.async {
self.dismiss(animated: true, completion: nil)
}
}
}
You can implement a function like isUserLoggedIn which will return true if token is saved in userDefaults. You need to check whether the user has logged in in the appDelegate's applicationdidFinishLaunchingWithOptions.Like
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if isUserLoggedIn(){
//showHomeViewController
} else{
//showLoginViewController
}
return true
}
func isUserLoggedIn() -> Bool{
if let accessToken = UserDefaults.standard.object(forKey: "access_token") as? String {
if (accessToken.characters.count)! > 0{
return true
} else {
return false
}
}
else {
return false
}
}

Related

problem when authorize then how to define provider in swifter.authorize method

i am facing problem to give provider name because i dont know how to give proper provider in swifter.authorize
my controller is where i am using login code
you can check func actiontwitter in which i have used provider then please suggest me how to use provider as parameter
i have installed swifter package in project
//
// twitterVc.swift
// socialLogin
//
// Created by ios on 19/11/22.
//
import UIKit
import FirebaseAuth
import Swifter
import SafariServices
struct TwitterConstants {
static let CONSUMER_KEY = "MY_CONSUMER_KEY"
static let CONSUMER_SECRET_KEY = "MY_CONSUMER_SECRET_KEY"
static let CALLBACK_URL = "MY_CALLBACK_URL"
}
class twitterVc: UIViewController {
var swifter: Swifter!
var accToken: Credential.OAuthAccessToken?
#IBOutlet weak var submitBtn: UIButton!
var provider = OAuthProvider(providerID: "twitter.com")
override func viewDidLoad() {
super.viewDidLoad()
self.isLoggedIn { loggedin in
if loggedin {
// Show the ViewController with the logged in user
print("Logged In?: YES")
} else {
// Show the Home ViewController
print("Logged In?: NO")
}
}
}
func isLoggedIn(completion: #escaping (Bool) -> ()) {
let userDefaults = UserDefaults.standard
let accessToken = userDefaults.string(forKey: "oauth_token") ?? ""
let accessTokenSecret = userDefaults.string(forKey: "oauth_token_secret") ?? ""
let swifter = Swifter(consumerKey: TwitterConstants.CONSUMER_KEY, consumerSecret: TwitterConstants.CONSUMER_SECRET_KEY, oauthToken: accessToken, oauthTokenSecret: accessTokenSecret)
swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { _ in
// Verify Succeed - Access Token is valid
completion(true)
}) { _ in
// Verify Failed - Access Token has expired
completion(false)
}
}
#IBAction func actionSubmit(_ sender: Any) {
self.actionTwitter()
}
func actionTwitter(){
//~~~~~~~~~~~~~~problem is here it is not taking provider as parameter
self.swifter.authorize(withProvider: provider as! ASWebAuthenticationPresentationContextProviding, callbackURL: URL(string: TwitterConstants.CALLBACK_URL)!) { (tokan: Credential.OAuthAccessToken?, resp: URLResponse) in
}
}
}
func failureHandler(){
}
extension twitterVc: SFSafariViewControllerDelegate{
func getUserProfile() {
self.swifter.verifyAccountCredentials(includeEntities: false, skipStatus: false, includeEmail: true, success: { json in
let userDefaults = UserDefaults.standard
userDefaults.set(self.accToken?.key, forKey: "oauth_token")
userDefaults.set(self.accToken?.secret, forKey: "oauth_token_secret")
// Twitter Id
if let twitterId = json["id_str"].string {
print("Twitter Id: \(twitterId)")
} else {
// self.twitterId = "Not exists"
}
// Twitter Handle
if let twitterHandle = json["screen_name"].string {
print("Twitter Handle: \(twitterHandle)")
} else {
// self.twitterHandle = "Not exists"
}
// Twitter Name
if let twitterName = json["name"].string {
print("Twitter Name: \(twitterName)")
} else {
// self.twitterName = "Not exists"
}
// Twitter Email
if let twitterEmail = json["email"].string {
print("Twitter Email: \(twitterEmail)")
} else {
// self.twitterEmail = "Not exists"
}
// Twitter Profile Pic URL
if let twitterProfilePic = json["profile_image_url_https"].string?.replacingOccurrences(of: "_normal", with: "", options: .literal, range: nil) {
print("Twitter Profile URL: \(twitterProfilePic)")
} else {
// self.twitterProfilePicURL = "Not exists"
}
print("Twitter Access Token: \(self.accToken?.key ?? "Not exists")")
}) { error in
print("ERROR: \(error.localizedDescription)")
}
}
}

Client Certificate Selection at run time and use as a URL Credentials using WKWebView is not working. (NSURLAuthenticationMethodClientCertificate)

func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
switch challenge.protectionSpace.authenticationMethod {
case NSURLAuthenticationMethodClientCertificate:
let query: [String:Any] = [kSecAttrAccessGroup as String: kSecAttrAccessGroupToken,
kSecAttrKeyClass as String : kSecAttrKeyClassPrivate,
kSecClass as String : kSecClassIdentity,
kSecReturnAttributes as String : kCFBooleanTrue as Any,
kSecReturnRef as String: kCFBooleanTrue as Any,
kSecMatchLimit as String: kSecMatchLimitAll,
kSecReturnPersistentRef as String: kCFBooleanTrue as Any
]
var result : AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess, let allItems = result as? [[String: Any]] else {
let errorDescription = SecCopyErrorMessageString(status, nil)
print(errorDescription as Any)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let items = allItems.filter { item in
return (item["tkid"] as? String)?.starts(with: "Bundle ID") ?? false
// return true
}
// **items are the certificates which is already added in device**
// Let user select which cert to use, handle pin entry and call the completion handler.
let alert = UIAlertController.selectCertAndPinEntryAlert(certs: items, completionHandler: completionHandler)
alert.show()
case NSURLAuthenticationMethodServerTrust:
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, credential);
case NSURLAuthenticationMethodHTTPBasic:
print("Basic auth")
default:
completionHandler(.useCredential, nil)
}
}
selectCertAndPinEntryAlert : this method allows user to choose the certificate which is already added in Keychain.
static func selectCertAndPinEntryAlert(certs: [[String : Any]], completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> UIAlertController {
// Select cert UIAlertController.
let alert = UIAlertController(title: "Select certificate", message: nil, preferredStyle: .actionSheet)
certs.forEach { item in
guard let certData = item["certdata"] as? Data else { return }
guard let certificate = SecCertificateCreateWithData(nil, certData as CFData) else { return }
alert.addAction(UIAlertAction(title: certificate.commonName,
style: .default,
handler: { action in
// Pin entry UIAlertController created after the user selected one of the certs.
let passwordAlert = UIAlertController(title: "Enter pin", message: nil, preferredStyle: .alert)
passwordAlert.addTextField { textField in
textField.isSecureTextEntry = true
}
passwordAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionHandler(.cancelAuthenticationChallenge, nil)
})
passwordAlert.addAction(UIAlertAction(title: "Ok",
style: .default,
handler: { action in
guard let pin = passwordAlert.textFields?.first?.text else { completionHandler(.cancelAuthenticationChallenge, nil); return }
** let secIdentity = item["v_Ref"] as! SecIdentity
let urlCredential = URLCredential(identity: secIdentity, certificates: nil, persistence: .forSession)**
// If this doesn't return a UserDefaults something is broken in the project and we might as well crash.
UserDefaults(suiteName: "App Group which used by app")!.writePin(pin)
**completionHandler(.useCredential, urlCredential)**
}))
passwordAlert.show()
}))
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionHandler(.cancelAuthenticationChallenge, nil)
})
return alert
}
Please provide the suggestion what i am doing wrong. What code i need to change?
Note : I am using Yubikey for fetching certificates and storing it into the keychain. Later All the added certificate popup i ll get to choose one.
I have tried this code but when i am entring the key to access the certificate, WKWebView is not taking this certificate as further process and i am getting URL Credentials as null in response.

session.dataTask synchronization issue

I have some trouble with the code below.
Though it works, there is some timing problem.
First let me say what I expect, I suppose the completion handler should be run when the data download is complete and my image ready to use. But reality seems to be quite different. When I try it the completion handler is called right away (I can see 'All OK' in the console) as if everything was instantaneous. But the image gets actually displayed much later. What am I missing?
let imageURL = URL(string: myURLString)
session = URLSession.shared,
_ = session.dataTask(with: imageURL) {[weak self]
(data: Data?, response: URLResponse?, error: Error?) in
if error == nil {
print("All OK")
self?.theImage = UIImage(data: data!)
self?.theView.image = self?.theImage
} else {print(error!)}
DispatchQueue.main.async {
self?.activityIndicator.stopAnimating()
self?.theView.setNeedsDisplay()
}
}.resume()
Can you try this code?
The control should not be actually going inside the handler at first call. And I think there are a few mistakes in your code as well which I pointed out earlier, especially the main thread is required for updating UI.
let session : URLSession
let config = URLSessionConfiguration.default
var resultFromServer: Any?
let responseResultData = [String:Any]()
session = URLSession(configuration: config, delegate: nil, delegateQueue: nil)
session.dataTask(with: request) { (data, response, error ) in
if error != nil {
DispatchQueue.main.async(execute: {
session.invalidateAndCancel()
})
}else{
let httpResponse: HTTPURLResponse = response as! HTTPURLResponse
do{
resultFromServer = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)
if httpResponse.statusCode == 200 || httpResponse.statusCode == 201 || httpResponse.statusCode == 202 || httpResponse.statusCode == 204 || httpResponse.statusCode == 203 {
if let respArr = resultFromServer as? [Any]{
//resp is array
}else if let respdict = resultFromServer as? [String : Any] {
//resp is dict
}else{
//resp is something else maybe string, etc
}
}
else {
//error status code something like 500, 404, etc
}
}
catch let error as NSError {
DispatchQueue.main.async(execute: {
session.invalidateAndCancel()
})
}
}
session.finishTasksAndInvalidate()
}.resume()

Swift 3 NTLM authentication

For a recent project I tried to pull some data from a server in the SOAP and oData format respectively, that is protected with a Microsoft NTLM authentication, and it has been a nightmare figuring out how to do it, none of the online examples really worked.
So here is my solution; I had to adapt, expand and combine a few different sources. I hope this helps someone in the future.
You might have to allow arbitrary loads!!
Adapted from:
https://gist.github.com/stevenschobert/f374c999e5cba6ccf09653b846967c83
https://blogs.msdn.microsoft.com/chiranth/2013/09/20/ntlm-want-to-know-how-it-works/
import UIKit
class ViewController: UIViewController {
var username: String? = nil
var password: String? = nil
lazy var conn: URLSession = {
let config = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
return session
}()
override func viewDidLoad() {
super.viewDidLoad()
username = "<username>"
password = "<password>"
ntlm()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func ntlm() {
let urlString = "<url>"
let url = URL(string: urlString)
let request = NSMutableURLRequest(url: url!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60000)
request.httpMethod = "GET"
let task = conn.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
print(response)
print(error)
print(String(data: data!, encoding: .utf8))
})
task.resume()
}
func doesHaveCredentials() -> Bool {
guard let _ = self.username else { return false }
guard let _ = self.password else { return false }
return true
}
}
extension ViewController: URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("got challenge")
guard challenge.previousFailureCount == 0 else {
print("too many failures")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodNTLM else {
print("unknown authentication method \(challenge.protectionSpace.authenticationMethod)")
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
guard self.doesHaveCredentials() else {
challenge.sender?.cancel(challenge)
completionHandler(.cancelAuthenticationChallenge, nil)
DispatchQueue.main.async {
print("Userdata not set")
};
return
}
let credentials = URLCredential(user: self.username!, password: self.password!, persistence: .forSession)
challenge.sender?.use(credentials, for: challenge)
completionHandler(.useCredential, credentials)
}
}

Swift / How to parse json from java spring code

I want to parse json from java spring code (Xcode 7.3 / Swift). I tried almost every solution from all sites.
When I register it gives the following error message at the console:
Response = Optional(<NSHTTPURLResponse: 0x7a7607e0> { URL: http://www.____.com/saveRegistrationJson.htm } { status code: 405, headers {
Allow = GET;
Connection = "Keep-Alive";
"Content-Length" = 1089;
"Content-Type" = "text/html;charset=utf-8";
Date = "Wed, 04 May 2016 12:21:34 GMT";
"Keep-Alive" = "timeout=15, max=100";
Server = "Apache-Coyote/1.1";
} })
before json
Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0." UserInfo={NSDebugDescription=Invalid value around character 0.}
This is my Code:
import UIKit
class RegistrationViewController: UIViewController {
#IBOutlet weak var userfnametextfield: UITextField!
#IBOutlet weak var userlnametextfield: UITextField!
#IBOutlet weak var useremailtextfield: UITextField!
#IBOutlet weak var userpwdtextfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func RegisterbtnTapped(sender: AnyObject) {
let fname = userfnametextfield.text
let lname = userlnametextfield.text
let Email = useremailtextfield.text
let pwd = userpwdtextfield.text
//check empty fields
if(fname!.isEmpty || lname!.isEmpty || Email!.isEmpty || pwd!.isEmpty )
{
DisplayMyAlertMessage("All Fields are required")
return
}
//store data
NSUserDefaults.standardUserDefaults().setObject(fname, forKey: "fname")
NSUserDefaults.standardUserDefaults().setObject(lname, forKey: "lname")
NSUserDefaults.standardUserDefaults().setObject(Email, forKey: "Email")
NSUserDefaults.standardUserDefaults().setObject(pwd, forKey: "password")
NSUserDefaults.standardUserDefaults().synchronize()
//send user data to server side
let myurl = NSURL(string: "http://www.____.com/saveRegistrationJson.htm")
let request = NSMutableURLRequest(URL: myurl!)
request.HTTPMethod = "POST"
let poststring = "fname\(fname!)&lname\(lname!)&email\(Email!)&password\(pwd!)"
request.HTTPBody = poststring.dataUsingEncoding(NSUTF8StringEncoding)
//request.HTTPBody = postData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data,response, error in
if error != nil{
print("Error\(error)")
return
}
print("Response = \(response)")
do{
var err : NSError?
print("before json")
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
print(json)
print("After json")
//print("demo : \(response?.description)")
guard let parseJSON = json else{
print("parsing json here:")
return
}
// guard let value = NSString(data: data!, encoding: NSUTF8StringEncoding) else{
// print("parsed")
// return
//}
//print("FirstName\(value)")
var requestValue = parseJSON[" "] as? String
print("result:\(requestValue)")
var isUserRegistered:Bool = false
if(requestValue=="Success") { isUserRegistered = true}
var messageToDisplay:String = parseJSON["Success"] as! String
if(!isUserRegistered){
messageToDisplay = parseJSON[" "] as! String
}
dispatch_async(dispatch_get_main_queue(), {
let myAlert = UIAlertController(title: "Alert", message: messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert)
let onAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { (ACTION) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}
myAlert.addAction(onAction)
self.presentViewController(myAlert, animated: true, completion: nil)
})
}
catch let error as NSError
{
print(error)
}
}
task.resume()
Help is very appreciated.