WebApi secured by Azure Active Directory called from JavaScript - sharepoint

I have the following scenario:
1.- A web api project in Azure, that I want to secure using Azure AD (I don't mind Token, cookie, whatever, as far as it meets the entire scenario)
2.- An Azure web site in asp.net MVC, also secured by Azure AD. This website has to call the web api controller with SSO (I'm using same Azure AD in the entire scenario)
3.- Some JavaScript code running in a page in SharePoint Online, also calling the web api controller in any secure way (The Office 365 tenant is also using same Azure AD). If you don't know about SharePoint, let's say I have an SPA project where I can only use Javascript and html (no server side code).
Following some of the MS Azure AD samples and some blogs from Vittorio Bertocci I'm able to get the points 1 and 2 working fine, using OWIN and Oppen ID connect. However, seems impossible to achieve point 3. As I'm inside a page in SharePoint Online, I can only use javascript, and not any server side code. I'd like to get a valid token for the current user, that is already logged in SP, and remember that SP uses same Azure AD that web api site.
Can I call the Azure AD and get a valid token, just from client code?
I'm open to any possible solution. I can do whatever in the web api project. If you are thinking in a SharePoint app with an appPart, and the appPart calls the web api from server side code, I agree that will work, but it's an option that is not allowed at the moment :(
Many thanks.

I have similar needs. While waiting for a Microsoft sponsored solution we’re working on the following approach.
3) in Your solution (i.e. HTML page with JavaScript, hosted in SharePoint Online and running in Browser) will call Services in 1) (i.e. Web Api Service layer in Azure).
In Our case we only want to validate that the calls made from SharePoint Online (via users browser, i.e. JavaScript) originate from a correct Office 365 / SharePoint Online user in our tenant.
We are opting out of using the App Model as we only want some simple HTML / JavaScript pages in our Intranet and don’t want App Webs. The Web Api server side code is kind of our “Web Part” code behind.
Change to the solution after trying it out and having workable code:
The auth cookies are ReadOnly and cannot be used. Instead we have registered one metod in our service layer as App in SharePoint Online (via appregnew.aspx). That methods url (e.g. https://cloudservice.customer.com/api/authentication/token) is registered as App start page in the app manifest and is deployed to a site Collection.
Now we can call our App via https://customer.sharepoint.com/sites/devassets/_layouts/15/appredirect.aspx?instance_id={GUID} i a jQuery ajax call and parse the result. AppRedirect sends the correct SPAuthToken which we use in our service endpoint (i.e. App start page) to call back to SharePoint and check context.Web.CurrentUser. User email is then stored in Table Storage with a generated Token which we send back to the caller (i.e. the jQuery ajax call to app redirect).
That token is then used in all other service layer calls in order to be sure of who is calling our service layer and in some cases perform authorization in our service layer.
Note, You can use the same approach in order to store Refresh and AccessToken in your client and provide that in all calls to your service from your client and use those tokens in order to do App Calls back to SharePoint. This enables HTML UI in SharePoint host webs and server code using user context in Azure service layer.

To follow up, ADAL.js has recently been released, and the ability to use CORS with O365 APIs was recently added, enabling a scenario for script clients to communicate with services protected by Azure AD, such as your Web API.
http://www.andrewconnell.com/blog/adal-js-cors-with-o365-apis-files-sharepoint

UPDATE 2018:
This is now supported by SharePoint Online and the SPFx development model, and officially documented, for instance here
Consume enterprise APIs secured with Azure AD in SharePoint Framework
Being said that the work done meanwhile by Vittorio, Kirk, and their teams, but extending that also to Andrew that has delivered great samples, is awesome; that doesn't really fully reply the original question because one of the requirements is to don't run the component as Add-in Part.
If you try to use ADAL JS (which starts its own OAuth flow) hosting that directly in a SP page, that's not going to work, or anyway you can expect a weird behavior for the user (cause of client redirects happening on the browser).
The solution proposed by Peter Karpinski is interesting, and will work matching the requirements in the original question, but requires quite some complexity and additional management/resources.
This recent article provides an alternative solution similar to Peter's one, but requiring less 'extras' and somewhat simpler, also reusing user's SP identity.
Consuming Azure Hosted Web API from SharePoint Online using JavaScript and Office 365 identities
and doesn't either require the use of ADAL on the client side and the implementation of custom security provider / token issuer on the server side.
The identity (cookie) will be passed via properly handling CORS (documentation) on both sides.
However, as you can read in my comments to that blog, this won't work normally with IE due to its security zone implementation. You'll have to be sure you have control on IE security zones on the clients, or have an alternative solution specific for IE.

As of today AAD does not support the OAuth2 implicit flow (or OpenId Connect variants) hence you can't obtain a token from AAD using a user-agent (browser), regardless of whether you hit the wire handcrafting the protocol or using a library.
However keep an eye on future announcements, as this is an important scenario for us!
HTH
Cheers,
V.
update we now support the implicit flow on our server, and we released a library for helping you consume the new feature: http://www.cloudidentity.com/blog/2015/02/19/introducing-adal-js-v1/
Thank youi for r your patience!

The fact that you say you can use only HTML/JS let me guess you're having a SharePoint-hosted App.
Azure AD Authentication Library (ADAL) doesn't provide yet in this moment support for HTML5.
I've been looking since a while (almost one year) on how to implement something as you say; but I couldn't find any working solution, which doesn't make use also of some 'code-behind'.
I'd suggest you then to move to a Provider-hosted App, where you'll be able to have some C# code, and make use of ADAL to retrieve and reuse the OAuth token.
Also, I think is worth to look at this documentation page:
Choose patterns for developing and hosting your app for SharePoint
at section Match your hosting pattern with your development goals

thanks for your help.
Well, it's not a SP-Hosted App, but it's same scenario. It's just a SP page in SP Online, so I can only use JS code like in a SP-hosted app.
As I said in my question, I agree the Provider hosted app is likely the right (or at least, the unique) solution, but that means to build and app, deploy it, and add teh appPart manually to the page (is not easy to package in a WSP). So, this solution is quite hard, when you only want to make some AJAX calls and show some data.
However, after all that I've seen, I think we can't do anything else. I'm gonna wait some more days to see if someone know any weird workarround that could work, and if not, I'll mark your answer as valid.
Thanks again!

Related

How to add Azure Authentication to my current web application which is using API as well?

So my project has got a two asp.net projects. One is for showing date(User Interface) and the another one is API(for background processes like login, database calls and etc.). Right now my app has Username and Password feature to login. I have setup a startup class in my API which authenticates the user and pass the user token. Now I want to add a feature to login through Azure portal.
Can anyone suggest me a good practice in this situation? Like I don't want to change my code and just add a feature. Should I make changes in API or Web or Both? Meanwhile I was reading about expose api in app registration. Will it be appropriate to use it just for login purposes?
Azure AD supports OAuth2, OIDC and SAML. See more information here. It is probably best to introduce the mechanism through the API first, since it would apply to the frontend as well (though slight modifications may be required there as well).

Open Azure App Service Endpoint to Only a Few Applications

I've implemented an ASP.NET Web API app as an Azure App Service. It has an App Registration, everything works as expected. I can hit the API from a browser and see all the JSON it returns. Now what I want to do is ensure that nothing except one or more applications from a set list can actually get anything from this endpoint. The applications needing access will all be custom ones in my organization/tenant. With all the flexibility and options, I'm having a very hard time determining what I need to do to lock the API down in this way.
I was envisioning having some client secrets the API knows about, and let the authorized applications supply them. Other methods would certainly be acceptable.
I'm certain this must be a duplicate question, but due to the plethora of information out there, and the myriad techniques for running applications on Azure, I can't seem to find just the right solution for my simple case.
It sounds like you have implemented interactive browser redirect-based authentication on the API.
Instead, you should implement JWT authentication on the API.
Then in Azure AD you can define permissions that can be granted to client applications.
In that way you can control which app can do what.
https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-1
https://joonasw.net/view/azure-ad-authentication-aspnet-core-api-part-2
https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-protected-web-api-overview
https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent

How to safely call Azure Function with function level authorization in Xamarin mobile app?

I'm making an iOS/Android app using Xamarin (not Xamarin.Forms, just regular Xamarin). I'm using the shared library set up rather than PCL. I want my app to call an Azure function but I'm unsure of the safest/best way to handle this. I have it set to "Function" for the "Authorization level". The test URL includes the "?code=..." portion in it. I was under the impression that if I put that in my C# code with the "code" value exposed that it was considered a bad idea from a security perspective.
I'm lost as to the safest/best way to deal with this. I've read that setting it in app.config is also a bad idea. I found some references for a web app that suggest using the connection strings that are available in the azure portal, but since this isn't a web app, I'm unsure of how I'd actually retrieve those values in my code (or if that's even possible).
So how would you suggest I handle setting the value for "code" so that I can call my function and avoid a security problem?
UPDATE: Providing more info as per request:
I'm using MSAL to authenticate my users with a B2C active directory. I already have that part working and have received a token authenticating the user.
I also just now enabled authentication in my functions.
I was under the impression that to call my function from my mobile client I had to make a new HttpRequestMessage. I'm unsure of then what I'd place in it to pass my token along.
Just to make sure I understand, your concern is about embedding secrets (the ?code=XXX value) in your iOS/Android app, correct? If so, yes, this is generally considered bad security practice. It's best to assume that anyone who can download your app will have the ability to discover these secrets and use them any way they want.
The recommended way to authenticate with a backend service, such as Azure Functions, from a mobile device is to use interactive authentication - i.e. some kind of OAuth flow. You can build it yourself, or you can use the built-in functionality of Azure Functions and Azure App Service to help you (Azure Functions is built on top of App Service). Here is a resource which might be useful:
https://learn.microsoft.com/en-us/azure/app-service/app-service-authentication-overview
https://contos.io/working-with-identity-in-an-azure-function-1a981e10b900#.vcjit3ntw
The API Key (code) is indeed not meant to be used by clients you distribute externally, so it shouldn't be used by your mobile app.
The most straight forward option here would be to use the built in App Service Authentication features with Azure Functions and implement an authentication flow in your app, which would allow you to securely authenticate the user.
Sharing more information about your scenario may help identify alternatives.

Azure Mobile App Authentication using Xamarin

I read these two articles 1.here and 2.here to find out what is best way to perform authentication against an Azure Mobile App when the API on the server is using Claims based custom authorization and the Xamarin client calling it is using the MobileServiceClient framework. I am unable to finalize which of the two examples in those links is the better way to go.
In the first link there doesn't seem to be any dependency on platform specific code like it has in the second link, which means I don't need to write any code in the Driod or IOS or Windows projects and can get away with doing everything in a class library itself.(Am I right here?)
Also, the first link seems to not require any provider like the second link does because I am invoking a direct service call to a Url. The second link on the other hand only seems to support Facebook, Twitter, MicrosoftAccount, Google and WindowsAzureActiveDirectory. The mandatory MobileServiceAuthenticationProvider parameter doesn't seem to provide for Custom Authentication against a sql server based User table. I am not sure about this part and cant find documentation that says otherwise.
If LoginAsync doesn't provide for Custom Authentication then its clear that I will need to follow the InvokeApiAsync route. If it does provide it then the question is: should I write platform specific(Droid/IOS/windows) code in each target project like in the second link or should I handle all the service calls in a class library as can be done in the example shown in the first link? In other words should I go with LoginAsync or InvokeApiAsync? Which of the two is the recommended way?
The first article shows off custom authentication, as you intimated. The second article shows off App Service Authentication, which has a known list. If you need to do a custom username/password, then go with the former. If you need to go with social auth or enterprise auth, then go with the latter.
My general recommendation is don't require the user to create yet another username unless you have to - which means social authentication for consumer apps and enterprise authentication via AAD for enterprise apps.
My other recommendation is to always use the client SDK for doing the authentication part. This allows you to follow the very latest practices from the provider (facebook, twitter, etc.) in respect to security, refresh tokens and other authentication requirements. Once you have the provider token, it's easy to swap it for an Azure Mobile token by using LoginAsync() with a token. See the Azure Documentation for information on this.
In all cases, you are going to need platform specific code - that means using the DependencyService (as in the second example) to execute your login code. I generally create a singleton class that wraps the MobileServiceClient in the PCL. Then create an ILoginProvider interface which has LoginAsync/LogoutAsync code in it to handle the platform dependency code. My singleton class then calls the DependencyService to get the code. You can find an example in my GitHub Repository that covers iOS, Android and UWP.

Best practice to implement Web API authentication in a SPA web shop

At the moment we are building a web shop as a SPA application. All the SKU information is provided by a Web Api 2 service.
Of course the web shop is publicly available to every visitor, and currently there is only one user who can log in to manage the web shop: the administrator.
For the administrator we built in the basic authentication with the bearer token, as a lot of samples on the internet shows us, but now we need every user to log in before they can see any product. Not really what we have in mind for a web shop ;-)
What we would like to implement is that our Web Api is not available to the world but only for our SPA application. Every blog post or tutorial on authorization seems to assume that there is always a user that needs to log in, in our case there is only one user: the administrator.
The AllowAnonymous attribute makes specific API calls available to the world again, so that's also a dead end.
Basically it comes down to preventing any other apps (web or mobile) to fetch the data from our Web Api.
What would be the best and most secure approach to secure our Web Api without having the anonymous visitors of our web shop to log in?
Solution for now: Altough I'm not 100% happy with this solution, it will work for now. We implemented the OAuth Implicit flow with CORS enabled for specific domain.
You should take a look at the OAuth 2.0 client credentials flow. The client in OAuth speak is the application and not the user using the application. This way you can make sure only your SPA app can access the backend API.
The parts that only should allow access to the administrator, you can decorate with the [Authorize(roles = administrator)] attribute, which prevents any other roles from having access.
I think Json Web Token could help you with this. This article has more information about using Json Web Token for granular authorization of your web api.
OAuth 2.0 is inherently insecure, and solely relies upon SSL. It has no encryption, and most of the latest web api gurus are suggesting that it's dead. This again is relative to what you need the security for. If it's for a social SPA where the data isn't financial or medical, for example, and good enough SSL security is ok, then perhaps OpenID or OAuth2 is suitable.
A much better solution is to implement Identity 2.0 for the Web API authentication flow, and then utilize something like Hawk Protocol for HTTP MAC implementation. Check this out : https://github.com/webapibook/hawknet for an example.
For OAuth2 framework and a extensible solution, check out Thinktecture.IdentityServer3 on GitHub
For a lightweight .net 4.5 Web API Tokenization solution, check out Thinktecture.IdentityServer2 on GitHub.
Hope it helps.

Resources