Xamarin Authenticate and Authorize Users with my Web Api - asp.net-web-api

I've been searching for a solution that makes sense for the past few days, so forgive me if I overlooked something or am ignorant to the correct path.
I have an existing Website built with asp.net framework MVC where users register for Individual Accounts and are stored in a MSSQL Database. I'm creating a Xamarin.Forms app where we want users to login with their website credentials.
I've been looking at Microsoft docs to try and accomplish this. In the past I created an Apache Cordova app (2014) that communicated in a similar fashion successfully (potentially in an insecure way) that called the /Token endpoint and Authenticated the user with 'grant_password' flow and returned the user data to the app.
So I landed on this documentation: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth-ropc
However, from what I can gather it basically says this should be avoided moving forward and a MSAL approach should be used if possible.
After reading through hours and hours of documentation trying to make sense of it all, I can't seem to grasp what my options are. It seems to me that in any MSAL flow, users will have to login with Microsoft accounts or other social accounts (facebook, google).
Am I missing something?
Am I going to have to go against Microsoft's advice and end up storing the client_id and client_secret within the Xamarin app source code? Which from everything I've read is a big security concern, especially with Android apps.
References: 1. Restrict API requests to only my own mobile app 2. How to secure an API REST for mobile app? (if sniffing requests gives you the "key")
Any help or direction would be really appreciated. Thank you

Your focus should be on requirements + understanding preferred designs rather than jumping to a technology.
DIRECTION
Standard modern systems look like this:
Mobile apps use OpenID Connect to sign users in
Authorization Server issues access tokens to the mobile app
APIs authorize requests via JWTs containing scopes and claims
Aim to make iterative steps towards this type of architecture.
PATTERNS
Plug in an Authorization Server, which uses your existing database as a credential store
Mobile app uses AppAuth Libraries to sign users in and receives access tokens
Back end can handle JWTs without data security risks
DIFFICULT AREAS
Your existing back end may have no support for mobile clients, and be too web focused - eg requiring cookies to access data, so may need to be split in be into 2 entry points.
Choosing an Authorization Server (while you are learning) is difficult, because you may not know what you want yet.
The mobile app will spin up the system browser and present a login page from the Authorization Server, so the login UX could be unexpected.
STEP 1
Ensure that you can authenticate from the mobile app, then make API calls with JWTs and ensure that requests for data are properly authorized. This could use ropc and involve a temporary API. But the deliverable should be that your back end now supports calls from mobile apps.
STEP 2
Integrate AppAuth into the mobile app, which is tricky but there are resources online such as Curity Mobile Guides. Update the mobile app to use the Code Flow and integrate an Authorization Server, then deal with connecting to credential stores.
SUMMARY
This stuff is hard and reflects the cost of modernising architectures. It requires people agreement as well as the technical stuff. Happy to answer follow up questions if it helps.

Related

Multi Domain with single login,

I have been planning to create a laravel+vuejs apps stretching across subdomains (presentation creator, forms creator, polls creator etc.,each in a subdomain) and will have 2 version of the same web app (indian version with different languages and content and international with different language and content) in 2 different domain say domain.in and domain.com but I want users from any app or domain to login with the single user login say from passport.domain.com we have WAP versions of the websites served from wap.domain.in and wap.domain.com and also mobile apps for both.
Now, normal users based on the userid and password, the user from .com domain will
be able to access apps and content only from .com domain and .in
will be able to access only from .in
Users will be able to login using facebook, linkedin, google, etc.,
We will have only a single app for iOS and Android and based on the username and password the apps will be able to access corresponding domain.
wap sites will login using the same passport.domain.com
mobile app will be able to access data from the domain through an appID and Key.
others will be able to embed the presentations and forms into their website using an api key and secret.
certain users will be able to transfer data created in one domain to another user in the other domain
admin users will be able to transfer data from both domains.
other platforms may be able to login using the user id from this platform.
is all this part of SSO (Single sign on) ?
is this achievable in laravel ?
is it advisable to write the sign in server in a different framework ?
different tech like SAML Outh2.0 and Open ID with terms like Authorization, authentication and id provider make it all confusing and baffling for a start up.
can some one tell me what tech are involved in the above process. and what one should be aware before jumping in to start development.
That's a lot of questions :)
IS IT POSSIBLE?
OAuth 2.0 based technologies will give you the best options, since:
It has the most up to date app security options
It is designed to be web, mobile and API friendly
Access tokens are designed to cross domains
WILL OAUTH DO EVERYTHING?
No it will not - you will need to build most of the above behaviour yourself, and implement a software architecture, as for any other security technology.
An Authorization Server will externalise logins / passwords and issue tokens. Your apps will then need to implement 'flows' including:
Web token based security and session management
Mobile token based security and session management
API token validation and claims handling
Integrating third party security libraries
GUIDANCE
When new to OAuth tech the best choices and design patterns are not clear, as you indicate. If it helps, my blog has some details you may find useful, but it is not a simple journey:
Step by step tutorials and code samples
Design posts on the tricky areas
Blog Index
This is not a Solution but an article I stumbled upon which explain the terminologies involved in user authentication and SSO.
Laravel authentication an overview
Hope this helps others who are looking for an answer like me now or in future.

How to secure public API requests without authentication from registered users

I have stacked over the problem where I cannot understand how organisation secure theirs public apis from any person who collects data.
I know we use passport and other ways of auth tokens in order to protect private info from unauthorised user.
But there are things like public Search Engine that doesnt need user to be authenticated in order to find on Facebook a person via search or access Profile info page. Which means there are open public api's that does not required authentication from user.
But going through couple of organisations I did not manage to get any public api request that I could access via Postman or simple via url.
So I am interested how do organisation protect their public api's from requests.
How the frontend send requests to those public (kinda private api), or even if it has some sort of default api key for all sort of public api calls, how they secure those from people, if in our modern browsers we can access Local Storage or Cookies where we can extract that public api_token
I am confused over MERN STACK and Laravel + SPA React application.
Developing public routes for api calls they are all accessible from browser url or postman unless if the route is private and requires auth_token from passport or jsonwebtoken that is already requiring user to be registered. But I am trying to achieve in my application for users to be able to search and access Product Details without authentication.
But obviously I would not like if any sort of Big Data engineer would easily steal all public data from my web application unless if he is not lazy and doing html parsing for each public Product Details page.
So how do I secure those above described public api routes in my backend application.
And how does it do big organisations like Facebook, Google, LinkedIn and etc.
The reason why I am asking this question, because it is so easy to find some MERN Stack course and they will teach you how to handle authentication for authorised users and so one. Or even the LAMP technologies. But no one explains how to protect this data without requiring any user to be signed in.
Thanks you very much in advance to any person who is going to answer this long and very much confusing question.
But there are things like public Search Engine that doesnt need user to be authenticated in order to find on Facebook a person via search or access Profile info page.
When I was coding in PHP and working with Prestashop e-commerce I have used a Crawler/Bot similar to the one in this gist, but this can be easily spoofed, because it's based on the HTTP_USER_AGENT. A better approach here is to use IP addresses to lookup the good know crawlers, aka the ones from searches engines like Google and Bing, but this will not work for keeping at bay the bad crawlers and bots. because they switch IP addresses very frequently.
But going through couple of organisations I did not manage to get any public api request that I could access via Postman or simple via url.
Companies like Facebook or even smaller ones, that have a good amount of resources at their disposal, use Artificial Intelligence(AI) to try to draw the line between Who is doing good and bad requests, and this type of software is known as User Behavior Analytics (UBA):
User behavior analytics (UBA) as defined by Gartner is a cybersecurity process about detection of insider threats, targeted attacks, and financial fraud. UBA solutions look at patterns of human behavior, and then apply algorithms and statistical analysis to detect meaningful anomalies from those patterns—anomalies that indicate potential threats. Instead of tracking devices or security events, UBA tracks a system's users. Big data platforms like Apache Hadoop are increasing UBA functionality by allowing them to analyze petabytes worth of data to detect insider threats and advanced persistent threats.
So this must be why you have such a difficulty in getting through the APIs of companies like Facebook, but that doesn't mean it's not possible, because Hackers have being do it, and the number of data breaches occurring every year in big companies are a proof of that.
The reason why I am asking this question, because it is so easy to find some MERN Stack course and they will teach you how to handle authentication for authorized users and so one. Or even the LAMP technologies. But no one explains how to protect this data without requiring any user to be signed in.
Well that may be because of a common misconception among developers that don't really understand the difference between Who vs What is doing the request to the API server.
The Difference Between WHO and WHAT is Accessing the API Server
I wrote a series of articles around API and Mobile security, and from the article Why Does Your Mobile App Need An Api Key? I will quote the following:
The what is the thing making the request to the API server. Is it really a genuine instance of your mobile app, or is it a bot, an automated script or an attacker manually poking around your API server with a tool like Postman?
The who is the user of the mobile app that we can authenticate, authorize and identify in several ways, like using OpenID Connect or OAUTH2 flows.
Think about the Who as the user your API server will be able to Authenticate and Authorize access to the data, and think about the What as the software making that request in behalf of the user.
So, in my opinion a lot of Developers are not aware of this difference between Who and What in a request, therefore they concentrate in solutions for the Who.
Possible Solutions
So how do I secure those above described public api routes in my backend application. And how does it do big organisations like Facebook, Google, LinkedIn and etc.
This organizations are using very sophisticated UBA solutions that may not be in the reach of every organization in terms of cost or because they are proprietary solutions, but other solutions exists, and you can read the section Defending the API Server on this other reply I gave to the question secure api data from calls out of the app to understand how you can gradually improve the security of an API server for a web app.
If you also need to secure the API server for requests from a mobile app, then you can lock it down with a very high degree of confidence to your mobile app, by employing the Mobile App Attestation concept, and you can read more about in this reply I gave to the question How to secure an API REST for mobile app?.
Do you Want to Go the Extra Mile?
I cannot finish any response to a security question without give a reference to the excellent work from the OWASP foundation.
For Web Apps
OWASP Web Top 10 Risks
The OWASP Top 10 is a powerful awareness document for web application security. It represents a broad consensus about the most critical security risks to web applications. Project members include a variety of security experts from around the world who have shared their expertise to produce this list.
The Web Security Testing Guide:
The OWASP Web Security Testing Guide includes a "best practice" penetration testing framework which users can implement in their own organizations and a "low level" penetration testing guide that describes techniques for testing most common web application and web service security issues.
For Mobile Apps
OWASP Mobile Security Project - Top 10 risks
The OWASP Mobile Security Project is a centralized resource intended to give developers and security teams the resources they need to build and maintain secure mobile applications. Through the project, our goal is to classify mobile security risks and provide developmental controls to reduce their impact or likelihood of exploitation.
OWASP - Mobile Security Testing Guide:
The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security development, testing and reverse engineering.
For APIS
OWASP API Security Top 10
The OWASP API Security Project seeks to provide value to software developers and security assessors by underscoring the potential risks in insecure APIs, and illustrating how these risks may be mitigated. In order to facilitate this goal, the OWASP API Security Project will create and maintain a Top 10 API Security Risks document, as well as a documentation portal for best practices when creating or assessing APIs.
A lot of the time I have seen APIs secured via Basic Auth or OAuth. When you use Basic Auth you send an Authorization header with a base64 encoded username and password. Headers are encrypted when you connect with HTTPS / SSL.
OAuth is a bit involved, but follows a similar idea. Your OAuth token is send via encrypted headers as well. You can read more about OAuth here: https://www.digitalocean.com/community/tutorials/an-introduction-to-oauth-2

Organizing a secure channel between a Web app and a Native app

This question is kinda complimentary to "Share credentials between native app and web site", as we aim to share secrets in the opposite direction.
TL;TR: how can we securely share the user's authentication/authorization state from a Web Browser app to a Native Desktop app, so the same user doesn't have to authenticate additionally in the Native app?
TS;WM: We are working on the following architecture: a Web Application (with some HTML front-end UI running inside a Web Browser of user's choice), a Native Desktop Application (implementing a custom protocol handler), a Web API and an OAuth2 service, as on the picture.
Initially, the user is authenticated/authorized in the Web Browser app against the OAuth2 service, using the Authorization Code Grant flow.
Then, the Web Browser content can do one-way talking to the Native app, when the user clicks on our custom protocol-based hyperlinks. Basically, it's done to establish a secure bidirectional back-end communication channel between the two, conducted via the Web API.
We believe that, before acting upon any requests received via a custom protocol link from the Web Browser app, the Native app should first authenticate the user (who is supposed to be the same person using this particular desktop session). We think the Native app should as well use the Authorization Code flow (with PKCE) to obtain an access token for the Web API. Then it should be able to securely verify the origin and integrity of the custom protocol data, using the same Web API.
However, it can be a hindering experience for the user to have to authenticate twice, first in the Web Browser and second in the Native app, both running side-by-side.
Thus, the question: is there a way to pass an OAuth2 access token (or any other authorization bearer) from the Web Browser app to the Native app securely, without compromising the client-side security of this architecture? I.e., so the Native app could call the Web API using the identity from the Web Browser, without having to authenticate the same user first?
Personally, I can't see how we can safely avoid that additional authentication flow. Communication via a custom app protocol is insecure by default, as typically it's just a command line argument the Native app is invoked with. Unlike a TLS channel, it can be intercepted, impersonated etc. We could possibly encrypt the custom protocol data. Still, whatever calls the Native app would have to make to decrypt it (either to a client OS API or some unprotected calls to the Web API), a bad actor/malware might be able to replicate those, too.
Am I missing something? Is there a secure platform-specific solution? The Native Desktop app is an Electron app and is designed to be cross-platform. Most of our users will run this on Windows using any supported browser (including even IE11), but ActiveX or hacking into a running web browser instance is out of question.
The best solution : Single Sign On (SSO) using Custom URL Scheme
When I was checking your question, I remembered the Zoom app that I am using in my office. How it works ?
I have my Gmail account linked to a Zoom account (this is account linkage, which is outside the scope of implementation). When I open Zoom app, I can choose the option to login with Gmail. This opens my browser and take me to Gmail. If I am logged in to Gmail, I am redirected back to a page that asking me to launch Zoom app. How this app launch happen ? The application register a custom URL scheme when app get installed and the final redirect in browser targets this URL. And this URL passes a temporary secret, which Zoom application uses to obtain OAuth tokens. And token obtaining is done independent of the browser, a direct call with SSL to token endpoint of OAuth server.
Well this is Authorization code flow for native applications. And this is how Mobile applications use OAuth. Your main issue, not allowing user to re-login is solved. This is SSO in action.
There is a specification which define best practices around this mechanism. I welcome you to go through RFC8252 - OAuth 2.0 for Native Apps.
Challenge
You need to implement OS specific native code for each application distribution. Windows, Mac and Linux have different implementation support for custom URL scheme.
Advice
PKCE is mandatory (in IETF words SHOULD) for all OAuth grant types. There is this ongoing draft which talks about this. So include PKCE for your implementation too.
With PKCE, the redirect/callback response is protected from stealing. Even some other application intercept the callback, the token request cannot be recreated as the PKCE code_verifer is there.
Also, do not use a custom solution like passing secret through another channel. This will make things complicated when it comes to maintenance. Since this flow already exists in OAuth, you can benefit with libraries and guidance.
-----------------------------------------------------
Update : Protecting Token Request
While the custom URL scheme solves the problem of launching the native application, protecting token request can be challenging. There are several options to consider.
- Bind native application launch with a secret shared from browser
When browser based client launch the native client, it can invoke a custom API to generate a secret. This secret acts like a one time password (OTP). User has to enter this value in native app before it obtain tokens. This is a customization on top of Authorization code flow.
- Dynamic client registration & Dynamic client authentication
Embedding secrets into public clients is discouraged by OAuth specification. But as question owner points out, some malicious app may register itself to receive custom URL response and obtain tokens. In such occasion, PKCE can provide an added layer of security.
But still in an extreme case, if malicious app registers the URL plus use PKCE as the original application, then there can be potential threats.
One option is to allow dynamic client registration at the first time of application launch. Here, installer/distribution can include a secret that used along with DCR.
Also, it is possible to use dynamic client authentication through a dedicated service. Here, the application's token request contains a temporary token issued by a custom service. Custom service obtain a challenge from native application. This may be done through totp or a cryptographic binding based on an embedded secret. Also it is possible to utilize OTP (as mentioned in first note) issued through browser, which needs to be copy pasted manually by end user. Once validated, this service issue a token which correlate to the secret. In the token request, native client sends this token along with call back values. This way we reduce threat vectors even though we increase implementation complexity.
Summary
Use custom URL scheme to launch the native application
Browser app generate a temporary secret shared with a custom service
At native app launch, user should copy the secret to native app UI
Native app exchange this secret with custom service to obtain a token
This second token combined with call back authorization code (issued through custom url scheme) is used to authenticate to token endpoint
Above can be considered as a dynamic client authentication
Value exposed to user can be a hashed secret, hence original value is never exposed to end user or another client
DCR is also an option but embedded secrets are discouraged in OAuth world
As you mentioned, using a custom protocol handler is not a safe way to pass secrets, since another app may handle your protocol and intercept that secret.
If you are imposing a strict constraint that the communication channel between the native app and the web app is initiated from the web app, and that the native app has not previously established a secure channel (e.g. shared secret which could encrypt other secrets), then it is not possible to safely transmit a secret to the native app.
Imagine if this were possible, then PKCE would be redundant in an OAuth 2.0 Code Flow, since the server could have safely transmitted the access token in response to the authorization request, instead of requiring the code_verifier to be provided with the grant when obtaining the access token.
Just got the following idea. It's simple and while it doesn't allow to fully automate the setup of a secure channel between Web Browser app and the Native app, it may significantly improve the user experience.
We can use Time-based One-Time Password algorithm (TOTP). In a way, it's similar to how we pair a Bluetooth keyboard to a computer or a phone.
The Web Browser app (where the user is already authenticated) could display a time-based code to the user, and the Native app should ask the user to enter that code as a confirmation. It would then use the code to authenticate against the Web API. That should be enough to establish a back-end channel between the two. The life time of the channel should be limited to that of the session within the Web Browser app. This approach might even eliminate the need for a custom protocol communication in the first place.
Still open to other ideas.
You could try driving the synchronization the other way:
Once the user is authenticated into the web app, launch the native app from the web app via the custom URL scheme.
If the native app is not authenticated, connect securely to the backend over HTTPS, create a record for the native app, retrieve a one time token associated with that record and then launch the web app in the user's browser with the token as a URL parameter.
Since the user is authenticated in the browser, when the server sees the token it can bind the native app's record with the user account.
Have the native app poll (or use some other realtime channel like push notifications or a TCP connection) the server to see if the token has been bound to a user account: once that happens you can pass a persistent auth token that the native app can store.
Did you think about using LDAP or Active Directory?
Also OAuth2 could be combined, here are a related question:
- Oauth service for LDAP authentication
- Oauth 2 token for Active Directory accounts
SSO should be easier then too, furthermore access-rights could be managed centralized.
Concerning general security considerations you could work with two servers and redirect form the one for the web-application to the other one after successful access check. That 2nd server can be protected so far that a redirect is required from the 1st server and an access check could be made independent again but without need to login another time, might be important to mention here the proposed usage of Oracle Access Manager in one linked answer for perimeter authentication.
This scenario with two servers could be also hidden by using a proxy-server in the frontend and making the redirects hidden, like that data-transfer between servers would be easier and secure too.
The important point about my proposition is that access to the 2nd server is just not granted if anything is wrong and the data are still protected.
I read here some comments concerning 2FA and some other ideas like tokens, surely those things increase security and it would be good to implement them.
If you like the general idea, I'm willing to spend still some time on the details. Some questions might be helpful for me ;-)
EDIT:
Technically the design in detail might depend on the used external authentication provider like Oracle Access Manager or something else. So if the solution in general sounds reasonable for you it would be useful to elaborate some parameters for the choice of a external authentication provider, i.e. price, open-source, features, etc.
Nevertheless the general procedure then is that the provider issues a token and this token serves for authentication. The token is for unique one-time usage, the second link I posted above has some answers that explain token-usage very well related to security and OAuth.
EDIT2
The Difference between an own OAuth2 / OIDC server and a LDAP/AD server is that you need to program everything by yourself and can't use ready solutions. Nevertheless you're independent and if everything is programmed well perhaps even a bit more secure as your solution is not public available and therefore harder to hack - potential vulnerabilities just can't be known by others. Also you're more independent, never have to wait for updates and are free to change whatever you want at any time. Considering that several software-servers are involved and perhaps even hardware-servers the own solution might be limited scale-able, but that can't be know from outside and depends on your company / team. Your code base probably is slimmer than full-blown solutions as you've only to consider your own solution and requirements.
The weak point in your solution might be that you have to program interfaces to several things that exist ready for business-frameworks. Also it might be hard to consider every single point in a small team, large companies could have more overview and capacity to tackle every potential issue.

Implement Web API with OAuth and a Single Page Application

We're developing an API and a single page application (that is one of more possible future consumers of it).
We already started on the web API, and basically implemented a system very similar to the one John Papa made in his course on pluralsight, named "Building Single Page Apps (SPA) with HTML5, ASP.NET Web API, Knockout and jQuery".
We now need to implement authentication and user managing in this application and need to find the easy way out to implement this in as little time as possible as we are in a hurry.
We realized the SPA template included in the ASP.NET update had very similar features to our needs, but we wonder what the best approach to implement a similar feature in our existing code.
We are novice developers, as you might figure.
Is it possible nstall some packages using the package manager, and voila, a simple membership and OAuth auth option be readily available?
Our use case is that we need to protect some resources on our API based on roles, and that one should be able to log in using a username and password, but also log in using ones facebook, google, or twitter account.
Found an interesting talk regarding the subject here: https://vimeo.com/43603474 named Dominick Baier - Securing ASP.NET Web APIs.
Synopsis: Microsoft’s new framework for writing RESTful web services and web APIs is appropriately enough called ASP.NET Web API. As the name applies, this technology is part of ASP.NET and also inherits its well-known security architecture. But in addition it also supports a number of new extensibility points and a flexible hosting infrastructure outside of IIS. There are a number of ways how to do authentication and authorization in Web API - from Windows to usernames and passwords up to token based authentication and everything in between. This talk explores the various options, and puts special focus on technologies like claims, SAML, OAuth2, Simple Web Tokens and delegation.
We eventually went with the SPA template, doing authentication on the API (separate MVC part).
Then the API would generate a unique token and redirect the user to the front-end with the token in url parameters.
The front-end then needs to send this token on every subsequent request.
Have a look here - Identity Server done by the security experts. This is all you need in one package.
In terms of OAuth, you would need to use Client-Side Web Application flow which the access token is issue immediately to the client and can be used.

ASP.NET Web Api security using Active Directory

I've searched the posts and have not found exactly what I'm looking for pertaining to my question. For example Security ... through AD asks more the question is it wise? My question is this:
We are implementing WCF applications and we are now putting WCF ... I mean ASP.NET Web Api ;)
into our server stack. I want to secure the services by requiring that the user log on to ADS, but if they already have logged on (via network login or other means) then I don't request a login. Rolebased authorization then occurs within the services.
I cannot find good discussions or examples of how I handle ADS authorization especilly through all of the future endpoints (tablet and phone).
My one thought was that the user does a login to ADS and the token then becomes what gets handled for security and rights. So now I'm a little bit concerned about how much coding has to be done to accomplish this. We are looking at FederatedServices to handle this in WCF but there is no such control in this weak API.
So I'm interested in any input or direct me to a great article on this. So far all I see is self-rolled security which our old server has and I do NOT want that crap again.
Oh yes, did I mention our target is single signon throughout our web services??? :)
Best place to start is Dominick's Thinktecture Identity for Web API. It is the de-facto security framework for Web API and supports token based identity.

Resources