I have several actions in my application (ASP.NET MVC) that are not intended to be called by browser clients, but from other external applications of my property, such as the Azure Scheduler and my mobile applications (Android)
For these actions to work as expected, a secret parameter and value must be passed.
public ActionResult SendPendingMessages(string secret = "")
{
if (!secret.Equals("hardcoded_secret"))
return null;
// Real stuff here...
}
The above action is called by my scheduler every 30 minutes and sends scheduled messages.
Other example:
public ActionResult DownloadUndownloadedMessages(string secret = "")
{
if (!secret.Equals("hardcoded_secret"))
return null;
// Real stuff here...
}
The above action is called by my android application.
It fetches unread messages.
From these external applications, I always use HTTPS, so I´m sure the hardcoded password (and the URL itself) is secret.
I don't like what I'm doing here. It gives me a bad feeling.
To name a few problems with this approach:
The hardcoded secret is a long term secret.
If other developer works on these external applications, they will know the secret URL
I don´t like that these actions can be called by just knowing the URL. I want to have something more solid than just hiding the URL.
The question is, finally:
What is the most correct way of achieving this purpose?
If a developer works at, for example, WhatsApp, and he´s fired. Can he call WhatsApp server´s actions with the knowledge he got from seeing the WhatsApp client app?
I think that your best approach is follow the WebAPI path and implements one of the answers the post bellow provides:
How to secure an ASP.NET Web API
Related
I'm following this documentation to implement OAuth2.0 in my flutter app and don't understand a few things, here is the code from the documentation:
import 'dart:io';
import 'package:oauth2/oauth2.dart' as oauth2;
// These URLs are endpoints that are provided by the authorization
// server. They're usually included in the server's documentation of its
// OAuth2 API.
final authorizationEndpoint =
Uri.parse("http://example.com/oauth2/authorization");
final tokenEndpoint =
Uri.parse("http://example.com/oauth2/token");
// The authorization server will issue each client a separate client
// identifier and secret, which allows the server to tell which client
// is accessing it. Some servers may also have an anonymous
// identifier/secret pair that any client may use.
//
// Note that clients whose source code or binary executable is readily
// available may not be able to make sure the client secret is kept a
// secret. This is fine; OAuth2 servers generally won't rely on knowing
// with certainty that a client is who it claims to be.
final identifier = "my client identifier";
final secret = "my client secret";
// This is a URL on your application's server. The authorization server
// will redirect the resource owner here once they've authorized the
// client. The redirection will include the authorization code in the
// query parameters.
final redirectUrl = Uri.parse("http://my-site.com/oauth2-redirect");
/// A file in which the users credentials are stored persistently. If the server
/// issues a refresh token allowing the client to refresh outdated credentials,
/// these may be valid indefinitely, meaning the user never has to
/// re-authenticate.
final credentialsFile = new File("~/.myapp/credentials.json");
/// Either load an OAuth2 client from saved credentials or authenticate a new
/// one.
Future<oauth2.Client> getClient() async {
var exists = await credentialsFile.exists();
// If the OAuth2 credentials have already been saved from a previous run, we
// just want to reload them.
if (exists) {
var credentials = new oauth2.Credentials.fromJson(
await credentialsFile.readAsString());
return new oauth2.Client(credentials,
identifier: identifier, secret: secret);
}
// If we don't have OAuth2 credentials yet, we need to get the resource owner
// to authorize us. We're assuming here that we're a command-line application.
var grant = new oauth2.AuthorizationCodeGrant(
identifier, authorizationEndpoint, tokenEndpoint,
secret: secret);
// Redirect the resource owner to the authorization URL. This will be a URL on
// the authorization server (authorizationEndpoint with some additional query
// parameters). Once the resource owner has authorized, they'll be redirected
// to `redirectUrl` with an authorization code.
//
// `redirect` is an imaginary function that redirects the resource
// owner's browser.
await redirect(grant.getAuthorizationUrl(redirectUrl));
// Another imaginary function that listens for a request to `redirectUrl`.
var request = await listen(redirectUrl);
// Once the user is redirected to `redirectUrl`, pass the query parameters to
// the AuthorizationCodeGrant. It will validate them and extract the
// authorization code to create a new Client.
return await grant.handleAuthorizationResponse(request.uri.queryParameters);
}
main() async {
var client = await loadClient();
// Once you have a Client, you can use it just like any other HTTP client.
var result = client.read("http://example.com/protected-resources.txt");
// Once we're done with the client, save the credentials file. This ensures
// that if the credentials were automatically refreshed while using the
// client, the new credentials are available for the next run of the
// program.
await credentialsFile.writeAsString(client.credentials.toJson());
print(result);
}
Where can I find the identifier and secret ? Is it shown in the /.well-known/openid-configuration page ? Also how do I implement these functions:
await redirect(grant.getAuthorizationUrl(redirectUrl));
var request = await listen(redirectUrl);
var client = await loadClient();
The documentation mentions that it is an imaginary function. How do I implement those functions?
OAuth with flutter is never going to be completely straight-forward on Android or iOS because it lacks deep integration with the OS, so you'll have to do a bit of per-OS configuration. And to be completely honest, it's not all that easy in native Android/iOS either.
And that plugin you're looking at seems much more focused towards a server application, which is why it doesn't make complete sense to a flutter developer. However, it isn't impossible to use it!
The main thing that enables OAuth to work is using either a Custom Url Scheme or a Universal Link. A Custom Url Scheme is something like com.myapp.customurlscheme:// - it's used instead of 'https'. A Universal link uses https and a website i.e. https://myapp.com/customurl/. An important difference is that to use a Universal link, you must control the website and upload a file that apple can check to know you've given the app permission to replace that website or that part of the website. If the user has the app installed, they will be shown it when they go to that url; if they don't, they'll be shown something by the website (normally a link to install the app).
In the case where you're an authenticating client with OAuth, you normally don't want to be replicating part of a website as all you're doing is making a callback (redirect) url, so you'll probably be using a custom url scheme. This has to be done by adding to either your AndroidManifest.xml or Info.plist files.
For iOS's Info.plist that looks something like:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string>[ANY_URL_NAME]</string>
<key>CFBundleURLSchemes</key>
<array>
<string>[YOUR_SCHEME]</string>
</array>
</dict>
</array>
And for the AndroidManifest.xml something like:
<activity>
...
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:scheme="[YOUR_SCHEME]"
android:host="[YOUR_HOST]" />
</intent-filter>
Once you have that set up, you can add listeners natively for when the app is 'opened' with one of those custom URLs. That's a bit of a pain, but thankfully someone has made a plugin that helps: Universal Links (and credit to them for the sample config above as I shamelessly stole it from their documentation). You can use its getInitialLink() method in your main function (or somewhere like it) and/or get a stream of links to listen for using getLinksStream(). I think that the second one is what you'll be using since the app is open already when you start the OAuth/OpenID workflow - so you'll start listening either right after the app is opened, or right before you start with the OAuth call.
Okay, so that was a lot. There's a reason for it though - what this has done is made a way for your app to receive redirects from a browser or other app. So if you handle that getLinksStream, you can then more or less receive a callback from the oauth2 server. You could set up some system where you create a future that waits for a particular link being passed through the linkstream.
So that covers
// Another imaginary function that listens for a request to 'redirectUrl'.
var request = await listen(redirectUrl);
Now we need to do something about that first imaginary function. Turns out in the app case, it's not imaginary at all - you need to launch that URL rather than having the page redirect as it would on a server. There's a plugin for that: Url Launcher
So where it's saying await redirect(grant.getAuthorizationUrl(redirectUrl));, what you actually want to be doing is launching grant.getAuthorizationUrl with url_launcher's launch() (with appropriate flags, that you'll have to figure out by testing. You may want to force using a browser, or not, depending on whether the OAuth server has an app that can handle auth for it. If they do, you probably want the url to open up in their app so the user is already logged in).
There's a couple more pieces to this puzzle that need to be fit in. The first is the redirectUrl that you have to pass into getAuthorizationUrl. What do I put in there, you ask?! Well, you use that nifty custom app scheme we set up earlier! So the redirect url will be something like com.myapp.customurlscheme://customurlredirect.
So the OAuth token provisioning workflow goes something like this:
you launch the auth url for the server
a login page is shown to the user, or a permissions page, or whatever the server does
once the user has approved the request, the server redirects the user back to your app (it might ask them "Do you want to open in " or something like it).
Your app receives the callback with the authorization code
Your app should request tokens using that authorization code (I assume that's handled by handleAuthorizationResponse).
Now, before you implement all that, there are a few things to think about.
If this were a server application, you could have a secure secret which proves to the OAuth server that your application is the client it claims to be. You would get that from the OAuth server and provision it directly to the server. However, because you're writing an app there is no (easy) way to provision that secure secret. So instead of using the normal OAuth you should be the OAuth authorization code flow with PKCE, and no client_secret. If that went over your head, you should do some reading up on PKCE - Auth0 has a good writeup. The OAuth server you're working with also has to support that, but if you do this without it your login process will be insecure.
The OAuth server you're communicating with has to both understand and accept custom url schemes. Most of the big ones do and they actually have documentation similar to this which should walk you through the same process (but not flutter-specific). And in fact they actually define what the custom url schemes should be - in Facebook's case if your app id is 1234567 then the custom url scheme would be something like fb1234567://.
I haven't looked that much into that library you're using, but you may want to make sure it actually supports the right OAuth workflow. If it designed as a server-side package as I suspect, it might not. In that case you might have to manually do the setup - which realistically isn't that difficult, you just have to generate a couple of URLs to match what the OAuth server expects which is pretty well documented and standardized.
That was a lot of information, but unfortunately OAuth2 isn't all that simple (and realistically, it can't be all that much simpler if it is to do what it needs to do). Good luck with your app!
I need to develop an API for web as well as mobile with NodeJS as backend. Since, both have common endpoints --> I was wondering how to handle error cases like for e.g. --> if there is an error and user is on web I can do res.redirect and the user will be redirected whereas if the request was from mobile then I will have to set an 'action' variable which will guide the mobile app to take the next action for e.g. ask the user to login again.
app.get('/users/musicList', function(req, res){
// check with db.
// lets say there is some error --> the API token is not valid so user needs to
// login
if (req was from web) {
res.redirect('/signin');
} else {
var result = {action : 'SIGNIN'};
res.status(200).json(result);
}
});
Is this the correct way to go ? It makes code look a bit messy. Any suggestions.
An Easy way to do this is to have two different endpoints for mobile and web. (Wait I have two more solution).But this would result in code duplication.
web: domain/route
mobile: domain/api/route
Another way is to have only api/route which uses only json. And to handle the error and routing in front end. This works if you are using front-end frameworks like angular and using AJAX requests.
Third one is to check for the client need and acting as in your question. Check this link for how to determine what client needs.
NodeJS : Validating request type (checking for JSON or HTML)
I am currently working on implementing a mobile app for our site that uses Ruby on Rails and Devise. The idea here is, at first, create a mobile login form that on successful login opens a web frame that is authenticated and allows the normal use of the (mobile optimised) site. Theoretically that should be possible.
I am having trouble with the following issues:
How do you get the pure session key for the user session via a json request? What methods can be used to manually generate it from devise, something that the sign_in(:user, user) method does?
Is it even possible to take that key and put it into the browser cookie the way it normally happens in devise, but on the mobile side?
I know that this is not the standard method of making mobile applications for the site, but I believe it should be possible.
You might want to consider using Devise Token Auth and treating your mobile application like just another webapp that requests permission from your main site. DTA is particularly nice since it takes care of managing the session tokens (renewing/expiring) and passing them onto the app requiring access. The issue is overriding your session controllers so that it automatically logs in after you already log in on the mobile app (or just rewriting your log in so it occurs in conjunction with the Rails site, rather than before). Considering you're already using Devise, this may also be more refactoring than you'd like.
If you want to put your authentication form on the mobile UI and pass the credentials over to the web frame, you need a way to pass data from the mobile app to the web frame.
How you accomplish this depends on what platform you're building on. I'm not really a mobile developer so I don't know for certain how difficult / easy these options are:
When opening the web frame, instantiate it with session data
Find a way to call methods on the client from the web frame. Something like getSessionData.
You could generate a fingerprint for the web frame, have the mobile UI send this data to the server, and then have the web frame authenticate with the server by sending the fingerprint.
Again, I'm not entirely sure how possible all these options are.
You should use token authorization and Android deep linking. It will allow you to login in the web browser and send a token to your app via deep linking.
OK, so I decided to make a webframe solution as follows, basically you post the login and password to a certain sign_in method specially designed to generate one-time sign in tokens for the application. You need two methods in the system to do that:
routes.rb
devise_scope :user do
get "sign_in_with_token/:token" => "sessions#sign_in_with_token"
post "get_login_token" => "sessions#get_login_token"
end
sessions_controller.rb (don't forget to add the method that increases the failed_sign_in_count on wrong password, otherwise that can allow brute force attacks)
def get_login_token
user = User.find_by_email(sign_in_params["login"])
password = sign_in_params["password"]
if user and user.valid_password?(password)
token = SecureRandom.hex(16)
user.update_attribute(:authentication_token, token)
render json: {token: token}, status: 200
else
render json: {error: "error"}, status: 403
end
end
and the method to sign in with that token
def sign_in_with_token
#user = User.where(authentication_token: params[:token], email: Base64.decode64(params[:email])).first
if #user
#user.update_attribute(:authentication_token, nil)
sign_in(#user, bypass: true)
end
redirect_to '/' # or user_root_url
end
That way the mobile app will work like this:
use the generic web frame to send ajax requests to the server and get that token for the user email if password is correct.
make a /sign_in_with_token/#{token from ajax}?email=#{base46 encoded email} link inside the app.
open that link inside the web frame and use the app as though you were logged in normally. Now the app can save email and password locally and use that logic to get the token again for another session. Later logging in will also be able to set the app id so that push notifications can be sent.
Appreciate any feedback or criticism on this solution.
I have been doing a lot of research recently on securing my app engine. Currently, I've been reading through the question below and the links in that question:
How do I restrict Google App Engine Endpoints API access to only my Android applications?
However, it doesn't answer my problem. My question is similar to the question above, restricting access to my endpoint API to only my app. The guy seemed to have got it working when he inputs a correct email into the credentials.
My question is if I can achieve the same results without having to input any credentials. I want it so that only my app can use my endpoint API so to prevent other apps from abusing it and using up my quota. I already got a client id for my android application, and have placed it within my #API annotation. To test if it worked, I made a random value for the client id in the #API notation of another api class. However, my app was still able to use methods from both class. Any help?
-Edit-
From reading from the docs and researching further, the endpoint way of authorizing apps is by authenticating the user and for my API to check if user is null. My question is that in the process of authenticating the user, is Google somehow able to read my app's SHA1 fingerprint and authorize it to its list of client ids? If so, how can I replicate this process in my endpoint so that I check the SHA1 fingerprint of the app making the request and compare it to a set value? I don't understand the mechanics behind the endpoints very well, so correct me if I am understanding this wrong.
If the android app has access, then the user has access. A motivated party has many options for inspecting your protocol, including putting the device behind transparent proxy or simply running the app through a debugger. I do suggest running your app through ProGuard before publishing, as this will make the process [a bit] more difficult.
Ultimately, you'll need to make your appengine API robust against untrusted parties. This is simply the state of the web.
How you can protect your endpoint API is described here: http://android-developers.blogspot.com/2013/01/verifying-back-end-calls-from-android.html
The secret is that you request a token from Google Play using the following scope: audience:server:client_id:9414861317621.apps.googleusercontent.com where 9414861317621.apps.googleusercontent.com is your ClientId.
Google Play will look up the id at your endpoints app and return a Google-signed JSON Web Token if it finds the id. Then you pass that id in with your request. Above article says you should pass it in with the body. I would possibly rather add another parameter for that because otherwise you can't pass your own entities anymore. Anyway, your server backend receives the token, and you ask Google as described if it is authentic, before you process the API request.
If you pass in the token using an extra parameter, you can catch it on the server side by adding HttpServletRequest to your endpoint signature and then using request.getHeader("Yourname") to read it out. Make sure you never add the parameter as a URL parameter as it may be logged somewhere.
public void endpointmethod(
// ... your own parameters here
final HttpServletRequest request
) throws ServiceException, OAuthRequestException {
request.getHeader("YourHeaderName") // read your header here, authenticate it with Google and raise OAuthRequestException if it can't be validated
On the Android side you can pass in your token when you build the endpoint api, like this, so you don't have to do it with each and every request:
Yourapiname.Builder builder = new Yourapiname.Builder(AndroidHttp.newCompatibleTransport(), getJsonFactory(), new HttpRequestInitializer() {
public void initialize(HttpRequest httpRequest) {
httpRequest.setHeader(...);
}})
Hope this helps you make your endpoints API secure. It should.
Hey i'm working on a web application in combination with an android app. Now i want in my mobile app that the user have to log in with the same user data like on the web application. So i want to send a username and a password to the controller and in the login action of this controller the user should be verified and the additional user id should be send back to the application (the id is used for several operations in the app). I looked for the Auth Component of CakePHP but i don't find any solution for my problem. I hope you can help me.
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user',$this->Auth->user());
if($this->name == 'Specific') {
// for the specific controller
$this->Auth->authenticate = array('Basic');
} else {
// everything else
}
}
checkout KVZ's rest plugin it may be of interest https://github.com/kvz/cakephp-rest-plugin
Not sure about what you need to do on the cakephp side of things, but if you want to have a set of account credentials stored securely and persistently on an Android device, I suggest you take a look at the AbstractAccountAuthenticator class.
The AuthComponent has a login() method you can use to manually login users. Depending on the Cake version you're using this method also checks the credentials you supply (actually Auth is completely restructured in 2.0 in a way that's much more useful for situations like yours, it's worth taking a look!).
You can send in the login credentials from your android app any way you please (XML, POST parameters), extract them in your login action and send them to the AuthComponent (or, in 2.0, write a custom authenticator object to handle it all).