how to enable SSL connections in alamofire - ssl

how to enable ssl connections just as the AFNetworking did:
self.manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:kHostName]];
self.manager.securityPolicy.allowInvalidCertificates = YES;
I had neither username nor password in my case, just a post request like this
https://domain/request
and the parameter:
email=123#abc.com
UPDATED
I had solved this case since I changed the parameter encoding form .JSON to .URL.

What about :
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(user: user, password: password)
.response {(request, response, _, error) in
println(response)
}
From https://github.com/Alamofire/Alamofire.
Invalid HTTPS certificates feature does not seem to be available yet - https://github.com/Alamofire/Alamofire/issues/116 .

Related

Uploading a file to WebDAV server using AlamoFire

I'm working on a private iOS14 app that will send files to a website server. User will just tap on a button, and the code will do all the work (hard coded username and password).
I would like to upload File.json to a WebDAV server (http://myWebsite.com/Files).
I would like to upload Image.png to a WebDAV server (http://myWebsite.com/Files).
The server requires a username & password (username: username, password: password).
func UploadJson(){
let username = "username"
let password = "password"
let credential = URLCredential(user: username, password: password, persistence: .forSession)
let fileURL = Bundle.main.url(forResource: "File", withExtension: "json")!
let http = "https://myWebiste.com/Files"
AF.upload(fileURL, to: http)
.authenticate(with: credential)
.response { response in
debugPrint(response)
}
}
I get a [Response]:
[Status Code]: 200
But no file has been uploaded.
I can use a Mac and login using the username and password and upload a file to the server, so I know the WebDAV folder is working. But the AlamoFire code isn't.
What am I missing? Do I need anything in the Files folder on the server to allow uploads? Currently it is empty.

after update to ios10, Alamofire4 request brings error status 401

After updating to xcode8 Alamofire4, my AlamofireRequest is not working, returning " status code: 401, headers" (unauthorised) on the request. The user authorisation is correct (I have checked the site). I do not have any compiler errors, but note that 'headers' is not highlighted in blue as usual, so am thinking that it is not recognising the headers properly. Am I doing something wrong with the 'headers' here?
let user = "sampleUser"
let password = "samplepass"
let credentialData = "\(user):\(password)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]
var checkUserEndpoint: String = "https://sample.com/ios1/user/\(uidEntered!).json"
print(checkUserEndpoint)
Alamofire.request(checkUserEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
I have already tried using this instead for the headers, but it made no difference:
var headers: HTTPHeaders = [:]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
also I tried this and it made no difference;
Alamofire.request(checkUserEndpoint,
method: .get,
parameters: nil,
encoding: JSONEncoding.default)
.authenticate(user: "sampleUser", password: "samplepass")
.validate()
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
// print(response.error)
I've done similar migration twice, and my educated guess is that one of your strings you pass to generate headers value is Optional, ie. user, password or base64Credentials; though generating Optional("thestring") instead "thestring". You can try to wrap the request like this:
if let user = user, password = password, base64Credentials = base64Credentials {
let headers = ["Authorization": "Basic \(base64Credentials)"]
var checkUserEndpoint: String = "https://sample.com/ios1/user/\(uidEntered!).json"
print(checkUserEndpoint)
Alamofire.request(checkUserEndpoint, method: .get, parameters: nil, encoding: JSONEncoding.default, headers : headers)
.responseJSON { response in
print(response.request)
print(response.response)
print(response.data)
}
This can happen eg. in a situation, where those values coming from the Objective-C code, where the variables are not marked nonnull.
... base64Credentials should not be optional though, as stated in the documentation.
The code is correct in both variants (manual header creation and Alamofire request .authenticate usage). Looks like server side issue, use curl/postman or any other REST client to receive success response from your server before continuing your app development.

cordova/phonegap 3.3: how to set user credentials in fileUploadOptions

I'm trying to make a file upload via Phonegap 3.3 file transfer plugin to a windows server secured by base authentication. Actually the normal conversation between my app and the server (per ajax) is working perfectly by sending my user credentials with every ajax call.
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.chunkedMode = false;
options.headers = {
'Authorization':authHeaderValue(db.getItem("user"), db.getItem("pass"))
};
and
authHeaderValue = function(username, password) {
var tok = username + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
};
This is what I tried so far (I found it on stackoverflow thread) but it gives me back a 401-unauthorized...
Pls. give me a short reply if you know something that could help me.
Best regards to you all,
Ingmar
Well, I do something similar but instead of "Basic" I use JWT for authentication. I'll show you the code I use:
options.headers = { 'Authorization': 'Bearer ' + app.session.getSess('token') };
And I use SessionStorage to save the token while it is valid.
If you wanna know about JSON Web Token
Another thing, remember to change the headers in your server, in my case something like:
('Access-Control-Allow-Origin','*');
('Access-Control-Allow-Methods','GET,PUT,POST,DELETE,OPTIONS');
('Access-Control-Allow-Headers','Content-Type, Authorization, Content-Length, X-Requested-With');

Use JSON request body rather than request parameters for Friend authentication in a Clojure Web Application

I am using Friend to build authentication into a Compojure web application.
I have defined a bespoke authentication workflow for Friend:
(defn authentication-workflow []
(routes
(GET "/logout" req
(friend/logout* {:status 200}))
(POST "/login" {{:keys [username password]} :params}
(if-let [user-record (authenticate-user username password)]
(workflows/make-auth user-record {:cemerick.friend/workflow :authorisation-workflow})
{:status 401}))))
The authentication part is factored out:
(defn authenticate-user [username password]
(if-let [user-record (get-user-for-username username)]
(if (creds/bcrypt-verify password (:password user-record))
(dissoc user-record :password))))
This works, but...
I am using AngularJS and having to post request parameters leads to some ugly Angular code (cribbed elsewhere from a StackOverflow answer):
$http({
method: 'POST',
url: '/login',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: username,
password: password
}
});
I would much rather do this much simpler call instead and just post a JSON object via the request body:
$http.post('/login', {username: username, password: password})
I tried to use ":body" in the authentication handler instead of ":params" but the value of :body seemed neither JSON nor Clojure to me so I don't know how I can use it:
{username me#myapp.com, password password}
I already have JSON request/response mapping workflows working correctly for my REST API handlers, and I checked already that the request headers (e.g. ContentType) were correct for JSON.
So can this be done with Compojure/Friend, and if so how?
Here is some working code and an explanation...
First the Friend workflow, using the request body:
(defn authentication-workflow []
(routes
(GET "/logout" req
(friend/logout* {:status 200}))
(POST "/login" {body :body}
(if-let [user-record (authenticate-user body)]
(workflows/make-auth user-record {:cemerick.friend/workflow :authorisation-workflow})
{:status 401}))))
Second, the authentication function:
(defn authenticate-user [{username "username" password "password"}]
(if-let [user-record (get-user-for-username username)]
(if (creds/bcrypt-verify password (:password user-record))
(dissoc user-record :password))))
Third, the Compojure application with middlewares declared:
(def app
(-> (handler/site
(friend/authenticate app-routes
{:workflows [(authentication-workflow)]}))
(params/wrap-keyword-params)
(json/wrap-json-body)
(json/wrap-json-response {:pretty true})))
Finally a fragment of AngularJS code to post the credentials (username and password come from an AngularJS model):
$http.post('/login', {username: username, password: password});
So what happens is this...
The Angular javascript code posts JSON to the web application login URL. The "Content-Type" header is automatically set to "application/json" and the request body is automatically encoded as JSON, for example:
{"username":"batman#batcave.org","password":"tumblerrocks"}
On the server, the middleware parses the JSON to a Clojure map and presents it to the handler via the ":body" keyword:
{username batman#batcave.org, password tumblerrocks}
The request is then routed to the custom Friend authentication workflow.
Finally the submitted values are extracted from the Clojure map and used to authenticate the user.
I suspect that your wrappers are applied in the wrong order. Check that ring.middleware.json/wrap-json-body is applied before (outside of) the friend wrapper.
e.g.
(def my-handler (wrap-json-body (cemerick.friend/authenticate ...)))
Otherwise, a quick fix might be to just wrap your whole app in ring.middleware.json/wrap-json-params

How to get github token using username and password

I am developing mobile apps using rhodes. I want to access private repo of github. I am having only username and password.
How to get token of given username and password.
Once you have only login and password you can use them using basic auth. First of all, check if this code shows you json data of desired repo. Username and password must be separated by a colon.
curl -u "user:pwd" https://api.github.com/repos/user/repo
If succeeded you should consider doing this request from code.
import urllib2
import json
from StringIO import StringIO
import base64
username = "user#example.com"
password = "naked_password"
req = urllib2.Request("https://api.github.com/repos/user/repo")
req.add_header("Authorization", "Basic " + base64.urlsafe_b64encode("%s:%s" % (username, password)))
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
data = res.read()
repository = json.load(StringIO(data))
You should use oauth instead: http://developer.github.com/v3/oauth/
Github users can create Personal Access Tokens at their application settings. You can use this token as an alternative to username/password in basic http authentication to call the API or to access private repositories on the github website.
Simply use a client that supports basic http authentication. Set the username equal to the token, and the password equal to x-oauth-basic. For example with curl:
curl -u <token>:x-oauth-basic https://api.github.com/user
See also https://developer.github.com/v3/auth/.
Send A POST request to /authorizations
With headers
Content-Type: application/json
Accept: application/json
Authorization: Basic base64encode(<username>:<password>)
But remember to take Two factor Authentication in mind
https://developer.github.com/v3/auth/#working-with-two-factor-authentication
Here You will receive a token which can be used for further request
Follow this guide at help.github.com. It describes how to find your api-token (it's under "Account Settings" > "Account Admin") and configuring git so it uses the token.
Here is the code to use GitHub Basic Authentication in JavaScript
let username = "*******";
let password = "******";
let auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var options = {
host: 'api.github.com',
path: '/search/repositories?q=google%20maps%20api',
method: 'GET',
headers: {
'user-agent': 'node.js',
"Authorization": auth
}
};
var request = https.request(options, function (res) {
}));