I have a rails app that uses Authlogic (from gem Communityengine). Now I want users to be able to login on a mobile device (Android in that case)
If I understand correctly I can use Http Basic Authentication to authorize specified actions, but the first step (I think) is, when the user enters his username and password in his Android device, to check wether that user exists and if that passwort is correct.
How would I do this?
The password is encrypted in the database (with a pw salt) So as I understand I can not just check the database if the provided user and password is correct.
Here are some Http headers from my app as the result from different curl requests I did, I guess Http basic auth is working since I get a correct HTTP code when I provide user credentials:
martin#martin-desktop:~/Applications$ curl -I username:password#localhost:3000/users/username/posts/new
HTTP/1.1 200 OK
Date: Sun, 21 Apr 2013 12:17:29 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.19
X-UA-Compatible: IE=Edge,chrome=1
ETag: "b9aa82940f06722b7d8e35ce46e3166d"
Cache-Control: must-revalidate, private, max-age=0
X-Request-Id: 291ee45de8cb95e06ed4e8e6d3d9408c
X-Runtime: 0.335820
X-Rack-Cache: miss
Set-Cookie: _AppName_session=BAh7CkkiD3Nlc3Npb25faWQGOgZFRkkiJTA0ZDRhYmQwNDJjYmM1OGJmZTkyNzJjMTc5NThkODg0BjsAVEkiDnJldHVybl90bwY7AEZJIj1odHRwOi8vZ2l2LWR1ZXJlbi51bmktbXVlbnN0ZXIuZGUvdXNlcnMvbWFydGluL3Bvc3RzL25ldwY7AEZJIhV1c2VyX2NyZWRlbnRpYWxzBjsARkkiAYAzYWM2NTJlMjgyODA5MTY1ODg2ZTBjNTdhNGUzYjk5MzRkNWQ0YTE4MDdlN2M0MWI2OTQzYmQyNzZmOGFlMGI5NjliMjU3NzZhYTg4NjBkM2U0Y2Q5YTJjYzgwODVlNzY5NDgwMzE2MmQ3NTBjYzlhMmQ4ZTViYTJmNjJmYzVhZQY7AFRJIhh1c2VyX2NyZWRlbnRpYWxzX2lkBjsARmkGSSIQX2NzcmZfdG9rZW4GOwBGSSIxYzlIQitJNXNYZHNGa2NCb2hKcm5DY2tIcHNxdWJuWDEydVdZUU5WSlMvZz0GOwBG--2b5f5687425d7ec414e34b79eb89e0b6b465c86f; path=/; HttpOnly
Status: 200
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
martin#martin-desktop:~/Applications$ curl -I localhost:3000/users/username/posts/new
HTTP/1.1 302 Found
Date: Sun, 21 Apr 2013 12:17:40 GMT
Server: Apache/2.2.22 (Ubuntu)
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.19
X-UA-Compatible: IE=Edge,chrome=1
Cache-Control: no-cache
X-Request-Id: 9e4b9094f99f5877c8fb79647a1a22f1
X-Runtime: 0.004657
X-Rack-Cache: miss
Set-Cookie: _AppName_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJWJhZGVlNzBjNjA0YmQ1MTgyYmI5OWMxZjcxOGIzZmZkBjsAVEkiDnJldHVybl90bwY7AEZJIj1odHRwOi8vZ2l2LWR1ZXJlbi51bmktbXVlbnN0ZXIuZGUvdXNlcnMvbWFydGluL3Bvc3RzL25ldwY7AEY%3D--32120aefd22c0748c352b016582451ede84225ca; path=/; HttpOnly
Location: localhost:3000/login
Status: 302
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
What I also found out so far is, that the Set-Cookie uses Base64 encoding (This is the encoding for the resulting string literal from http basic auth)
Any help is appreciated!
Nevermind I added this method, which checks for username and password validity and writes the result in the header:
def auth
authenticate_or_request_with_http_basic do |username, password|
if user = User.find_by_login(username)
response.headers['Auth'] = 'Password incorrect'
if user.valid_password?(password)
response.headers['Auth'] = 'Credentials correct'
end
else
response.headers['Auth'] = 'Username incorrect'
false
end
end
end
In my mobile application I just send a request to username:password#mysite.com and read the http header. Not sure if this is an elegant method or if it is inteded, but it works for now.
Related
After a lot of reading and Googling it seems I have made a complete setup for Google Cloud Messaging to send push-notifications. My missing link is the Reference_Ids that I must use to target apps. I have created a project and also added my apps to it.
When I send a push-request to GCM I get the following response:
{"multicast_id":7952352701122753715,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Alt-Svc: quic=":443"; ma=2592000; v="35,34"
Vary: Accept-Encoding
Transfer-Encoding: chunked
Accept-Ranges: none
Cache-Control: max-age=0, private
Date: Wed, 21 Dec 2016 16:12:43 GMT
Server: GSE
Content-Type: application/json; charset=UTF-8
Expires: Wed, 21 Dec 2016 16:12:43 GMT
}
And the error reads "InvalidRegistration".
So my questions are:
Where do I find my registration Ids?
And as a related follow-up question, where do I find Registration_Ids for everyone using an app or a specific group or user?
BTW: I found a related question, but it does not seem to have an answer to as where to find these Ids. StackOverflow post.
InvalidRegistration means that the registration token (registration id) you used is invalid (doesn't exist, wrong format):
Check the format of the registration token you pass to the server. Make sure it matches the registration token the client app receives from registering with Firebase Notifications. Do not truncate or add additional characters.
Make sure that you are using the correct and corresponding registration token to the device you intend to send the message to. For testing, I would suggest to make use of the Firebase Console too, so that you can see if the error still occurs from there.
For Android, you can retrieve the registration token by calling:
FirebaseInstanceID.getToken()
You may then choose to store the token to your App Server.
You should use Api server_key .
Go to firebase console -> click on your project -> click on gear icon -> project_setting -> cloud_messaging
I am trying to send Mailgun POST /messages API request in Android using retrofit library.
Following is retrofit request:
HTTP POST https://api:key-xxx/v3/sandboxxxx/messages
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
Content-Length: 148
from=Excited+User+%3Cmailgun%40sandboxxxxmailgun.org%3E&to=vir.jain%40gmail.com&subject=Hello&text=Testing+awesomeness
Response:
HTTP 401 https://api:key-xxx/v3/sandboxxxx.mailgun.org/messages (1966ms)
Server: nginx/1.7.9
Date: Mon, 15 Jun 2015 10:00:37 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 9
Connection: keep-alive
WWW-Authenticate: Basic realm="MG API"
OkHttp-Selected-Protocol: http/1.1
OkHttp-Sent-Millis: 1434362440805
OkHttp-Received-Millis: 1434362441086
Forbidden
When I try this same request on Postman, it works perfectly & email is sent properly. But when sending using retrofit library from Android fails with Forbidden.
My Retrofit API:
#FormUrlEncoded
#POST("/messages")
public void sendEmail(#Field("from") String from, #Field("to") String to, #Field("subject") String subject, #Field("text") String text, RestCallback objectRestCallback);
Base URL is:
https://api:key-xxx/v3/sandboxxxsandboxxxx.mailgun.org
Everything is form URL encoded. But I'm really not sure what going wrong.
Can anyone please help me out whats wrong with above API?
Thank you,
Mahavir
I added following authorization header with Base64 encoded string of API key to the request, it started working.
request.addHeader("Authorization", "Basic "+getBase64String("api:key-xxxYOUR-API-KEY>"));
#Selvin: Thanks so much for sending wiki link :).
you need to specify your mailgun region: mg.SetAPIBase(mailgun.APIBaseEU)
// Create an instance of the Mailgun Client
mg := mailgun.NewMailgun(yourDomain, privateAPIKey)
mg.SetAPIBase(mailgun.APIBaseEU)
I am currently following the instructions given here for cross-client validation in an Android-GAE app, so my users can give the Python backend off-line access to the G+ APIs on their behalf. That documentation also directs me here, which is really where I am having the trouble. I have successfully obtained an authorization code and sent it to the backend, but when the backend tries to exchange that code for access and refresh tokens I get "error:invalid_grant" with "error description: invalid code". To illustrate, when I copy the code and other needed info into a curl, the output is as follows:
curl -d "code=4/uG6moqbHvs9hgfG1HmEfT39zT1j0.Un-H_36OXGUWmmS0T3UFEsMwQpwOhwI&client_secret={MY_SECRET}&client_id={MY_WEB_CLIENT_ID}&grant_type=authorization_code" https://accounts.google.com/o/oauth2/token -v
* Adding handle: conn: 0x7fc359803a00
* Adding handle: send: 0
* Adding handle: recv: 0
* Curl_addHandleToPipeline: length: 1
* - Conn 0 (0x7fc359803a00) send_pipe: 1, recv_pipe: 0
* About to connect() to accounts.google.com port 443 (#0)
* Trying 74.125.28.84...
* Connected to accounts.google.com (74.125.28.84) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_RC4_128_SHA
* Server certificate: accounts.google.com
* Server certificate: Google Internet Authority G2
* Server certificate: GeoTrust Global CA
* Server certificate: Equifax Secure Certificate Authority
> POST /o/oauth2/token HTTP/1.1
> User-Agent: curl/7.30.0
> Host: accounts.google.com
> Accept: */*
> Content-Length: 219
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 219 out of 219 bytes
< HTTP/1.1 400 Bad Request
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: Fri, 01 Jan 1990 00:00:00 GMT
< Date: Sun, 12 Jan 2014 16:38:42 GMT
< Content-Type: application/json
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: 1; mode=block
* Server GSE is not blacklisted
< Server: GSE
< Alternate-Protocol: 443:quic
< Transfer-Encoding: chunked
<
{
"error" : "invalid_grant",
"error_description" : "Invalid code.[Email: \n\nToken Record:\nToken: \"4/uG6moqbHvs9hgfG1HmEfT39zT1j0.Un-H_36OXGUWmmS0T3UFEsMwQpwOhwI\"\nIssueDomain: \"206701529154-7d35h3g4a22aef8d78p6up1cdiq3pl4d.apps.googleusercontent.com\"\nIssueTimeSec: 1389544361\nExpirationTime: 1389544961\nTokenUsage: 3\nScope: \"https://www.googleapis.com/auth/plus.login\"\nScope: \"https://www.googleapis.com/auth/userinfo.profile\"\nScope: \"https://www.googleapis.com/auth/userinfo.email\"\nScope: \"https://www.googleapis.com/auth/plus.moments.write\"\nScope: \"https://www.googleapis.com/auth/plus.me\"\nScope: \"https://www.googleapis.com/auth/plus.profile.agerange.read\"\nScope: \"https://www.googleapis.com/auth/plus.profile.language.read\"\nScope: \"https://www.googleapis.com/auth/plus.circles.members.read\"\nServiceInfo {\n ServiceId: 226\n Info <\n [security_lso_auth_oauth2.EarlyIssuedTokenProto] <\n auto_approved: false\n access_token: \"ya29.1.AADtN_UyJ2wiWB7lh7btUiCwUyHzix_DrubjdSsTxA6drG-ZccPWaeZJa31sebPnRCHiFw\"\n refresh_token: \"1/ImSjHYLkFcBOwsCezBg2dKpcqko9by3nTIh_k33ZMds\"\n >\n >\n}\nRevoked: true\nAuthorizedBy: 0x866419b291\nOAuthCallbackUrl: \"urn:accounts.google.com:api_auth:programmatic:virtual_redirect_uri\"\nOfflineAccess: true\nRevokeOnPasswordChange: true\nClientManagedRevocation: false\nInBundle: true\n]"
* Connection #0 to host accounts.google.com left intact
}%
I'm having a lot of trouble making sense of this error message to determine why my authorization code might be invalid. I did notice that in the explorer logs, all logs are time-stamped an hour in the past (so when I post a log at 11AM, it appears in the explorer with a timestamp of 10AM). Could a timezone discrepancy somehow be causing the oauth2 servers to think I am submitting authorization codes that are too old? I already tried changing my system time to match the log time, to no avail. Does anyone know what could be causing my authorization code to be invalid? I have searched high and low for hours.
Shortly after posting this question, I discovered the answer myself. Posting it here in case others run into the same problem. I noticed that a similar error was occurring in Google API Invalid grant on one-time auth code from GoogleAuthUtil.getToken, and the reason was that the developer needed to request refresh/access tokens multiple times within the span of 10 minutes (which is the expiration duration of the one-time authorization code). Inspecting my explorer logs again, I saw that I have a bug in my android code causing my cross-client validation code to be run twice in rapid succession instead of only once like it's supposed to. The first time it's run, the refresh and access tokens are returned correctly. The second time, the error is generated.
In retrospect, the "revoked = True" part of the error message should have pointed me to the answer.
Im currently working on an app that will request GPS location updates. I have successfully implemented it as well as the latitude API and OAuth 2.0. It seems like the latitude API only reads the users last google latitude update. I dont know how to insert a new update into the latitude API.
An example would be https://play.google.com/store/apps/details?id=gaugler.backitude&hl=en
They are able to insert new gps updates directly to google latitude.
How can I achieve this?
This can be done with the current location insert() API call:
https://developers.google.com/latitude/v1/currentLocation/insert
used the oauth playground to Post the following to the api u ask about
IMO at {data, all u really need are latitude, longitude. You will have to check that.
POST /latitude/v1/location HTTP/1.1
Host: www.googleapis.com Content-length: 244 Content-type:
application/json Authorization: OAuth
ya29.AHES6ZTbG5HRDWduqeV60o_GWYagNg1BEk4c89V5ocSh0W2yc6FRYg
{"data":{"kind": "latitude#location", "timestampMs": "1355601946",
"latitude": "22", "longitude": "22", "accuracy": "40", "speed":
"10", "heading": "180", "altitude": "42", "altitudeAccuracy":
"50", "activityId": "xyzzzzzzz"}}
HTTP/1.1 200 OK Content-length:
158 Via: HTTP/1.1 GWA X-content-type-options: nosniff Etag:
"0UQtEv4nUExaO_EaPNLUB8rXY8M/mI3wNTFvwTjtI9TlZ9A9neseLn0"
X-google-cache-control: remote-fetch
-content-encoding: gzip Server: GSE Reason: OK X-xss-protection: 1; mode=block Pragma: no-cache Cache-control: no-cache, no-store,
max-age=0, must-revalidate Date: Sat, 15 Dec 2012 20:32:11 GMT
X-frame-options: SAMEORIGIN Content-type: application/json;
charset=UTF-8 Expires: Fri, 01 Jan 1990 00:00:00 GMT
{"data":{"kind":"latitude#location","timestampMs":"1355601946","latitude":22.0,"longitude":22.0,"accuracy":40,"speed":10,"altitude":42,"altitudeAccuracy":50}}
For dev against these api's you should consider 2 things:
debug on your stack will require that you inspect HTTP HEADERS, HTTP WIRE
so, look them up and figure out how to display
use the 'oauth playground' to simulate what your app will POST. Simply put, if it works in the playground combined with CURL client , you will know exactly what to do in your app.
I want to send the SOAP xml request to php server from android device, as shown below are required parameter for posting request. Currently i am not getting any method or sample to do achieve.Any suggest some samples.
POST /sample/server.php HTTP/1.0
Host: x.x.x.x
User-Agent: NuSOAP/0.7.3 (1.114)
Content-Type: text/xml; charset=ISO-8859-1
SOAPAction: ""
Content-Length: 551
Thanks