Dont get any scopes when calling my Azure AD OAuth web api - azure

I have a web api, using azure ad oauth authentication. I want my associates´ web sites to be able to use this api to display content on their public website. To clearify: No user should be needing consenting/grant anything and they are anonymous.
I have used this guide to set up my web api and this code ("Web Application to Web API"->WebApp-WebAPI-OAuth2-AppIdentity-DotNet-code) for my demo client.
The default scope/permission was assigned to client app in azure portal, like so
The actual problem I trying to solve is my different associates webpages should have different permissions. I was hoping to create different scopes and assign different associates client apps with different scopes and I could check if they for example has update_customer_x-scope.
All this "seems" to work ok. I get my authentication token and I am able to get content from the web api. BUT I dont get any scopes at all. Reading the first guide(web api) I see that you should be able to get the default scope by using the code:
if (ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/scope").Value == "user_impersonation")
{/*you have the default scope*/}
But I dont find anything here, and no scopes at all. Any clues?
This is the content of the JWT-token, as requested

The TodoListController.cs from WebApp-WebAPI-OAuth2-AppIdentity-DotNet just use the client credentials flow as astaykov commented for retrieving the access token without user interaction, at this time, if you decode your code via https://jwt.io/, you would not find the scp property.
For your requirement, you need to follow WebApp-WebAPI-OpenIDConnect-DotNet for calling a web API with the signed-in user's permissions.

Related

Authenticating with Azure EasyTables - Azure ActiveDirectory

I've been attempting to authenticate requests to an Azure App Service for some time now and I'm completely stumped, I just can't seem to get the Microsoft.Azure.Mobile.Client to accept and successfully authenticate against a known "good" token.
Overall, all I want is to be able to successfully pull up a web browser in Xamarin Forms, authenticate the user either with Azure, Google or other social authentication, and then use a token to authenticate against an Azure App Service (EasyTables), which I already have running but without authentication enabled. For some reason none of the resources I've found have provided an clear way of doing this, and I'd be grateful for any help.
Here's the main config of what I have so far:
I've got an app successfully reading and saving data tables to an Azure-hosting EasyTables implementation. Tables are read (and written) using the standard form:
var locations = (await App.MobileService.GetTable<Location>().ToListAsync());
The MobileServiceClient is instantiated in the App.xaml.cs file as follows:
public static MobileServiceClient MobileService = new MobileServiceClient("https://mywebapp.azurewebsites.net");
As I say above, this works fine when access to and saving from online services.
Going to the Azure Portal, I've activated "App Service Authentication" under Settings --> Authentication / Authorization, and I've also set up an Azure Active Directory Authentication Provider. Under this provider I've set up the Client ID of an Azure Active Directory instance (under Manage --> App Registrations).
Going back to Xamarin, I have successfully managed to authenticate against this using the approach by Steven Thewissen here. In particular, I've created an "MSAuthService" helper, which successfully pulls up a web browser, allows you to log in with Microsoft credentials, following which it's able to retrieve your account name and verious other things from Microsoft Graph - including the Access Token.
I'm now trying to use this access token to log into the MobileService I'm using to access EasyTables, using the following:
JObject auth_token_jobject = new JObject();
auth_token_jobject["authenticationToken"] = token;
var output = await App.MobileService.LoginAsync(
MobileServiceAuthenticationProvider.MicrosoftAccount,
auth_token_jobject);
However, whenever I do this, I still get an "Unauthorized" error, produced by the last line above.
I understand that others (e.g. here seemed also to have the same problem, but no resolution on that post.
Other things that I've tried, but haven't managed to get working completely. As above, the closest I've got, by successfully authenticating albeit through Microsoft Graph rather than with my web service specifically, is the process above:
Overview of Authorization with EasyTables etc here - although this doesn't seem to provide any clear code for Xamarin to authenticate against.
Latest Xamarin blog and explanatory materials (here and here, but although the process using await WebAuthenticator.AuthenticateAsync method appears to be a lot simpler than the example I was using above, there doesn't seem to be any detail provided about how you generate the URI required to call the authentication page, nor a step by step guide of how to implement it. Either way, I haven't managed to get it working...
If anyone has an easy way of getting hold of a valid token and then providing it to the MobileService client, I'd be most grateful. I suspect it's as simple of getting the token called back, for example from a Xamarin Essentials WebAuthenticator above, and then passing it with var output = await App.MobileService.LoginAsync(MobileServiceAuthenticationProvider.MicrosoftAccount,auth_token_jobject) but I just can't seem to get it working so far.
Thanks a lot!
Oliver.
There are a couple of issues here (on re-reading it a few times)
You are using MobileServiceAuthenticationProvider.MicrosoftAccount - you should be using "aad" instead.
AAD needs an access token - see https://learn.microsoft.com/en-us/azure/app-service/app-service-authentication-how-to#validate-tokens-from-providers for the details on what needs to be provided.
If the token you get back is really an MSA token, then you still need to provide an access_token field (and not an authenticationToken field)
If you don't need anything special, you should be able to just use .login() like this:
await App.MobileService.LoginAsync("aad", "your-method");
For more details on this, see one of the authentica

Starting using Google Sheets API cannot get configuration/token files

I need to get access at the sheets and I am following this guide to start to do that https://developers.google.com/sheets/api/quickstart/nodejs
But the button that enables google APIs doesn't work, all names I put on the project return an error.
I went on the API console and created a new project but I do not know how to get credentials files (if they are needed) and then I must create an URL for the OAuth page?
How to get OAuth crendetials manually
There different types of crendetials and the procedure to obtain them is slightly different depending on your situation.See here for the different scenarios.
In most cases (an exception is when using a service account), the first step is to set up an OAuth consent screen.
The consent screen is the screen your users see when they are prompted to agree to terms that are presented to them by your application
To set up a OAuth consent screen, go after chosing a project from the GCP console on APIs & services -> OAuth consent screen
You need to chose either your application is supposed to accessible only by domain internal users or also external (in the latter case you might need to submit your application for verification by Google, pontentially involving costs - depending on the scopes you use).
You need to provide an application name that your users will see (the logo is optional)
You need to specify which scopes your app will use
You can specify other properties, e.g. the Authorized domains (this is usually your website from which the users will be redirected to the consent screen when performaing some kind of action)
If you are not sure about the optional properties, leave them out for the start
Once you set up the authentication screen, the second step is to go on APIs & services -> Credentials
Read the Authentication overview to decide which credentials you need
For most applications you will want an OAuth client ID
The diffrent Application types are described here, to start with create a Web Application
Authorized JavaScript origins and Authorized redirect URIs is basically your Webpage from which the users will be redirected to authenticate and to which they should be redirected after authentication.
For local testing you do not need to specify those URLs
Once you create the OAuth2 client successfully, you will obtain the Client ID and Client Secret - your crendetials to incorporate into your code when using Google APIs.
If you click on the download button on the right side of your newly created credentials - it will generate a json file on your local machine from which the credentials will be read automatically if you follow the quickstart.
Alternatively you can paste the credentials directly into your code - see here for sample for different situations

Azure Mobile App Service APIkey

I created an Azure Mobile App Service which is currently accessible 'Anonymously'
Anonymous access is enabled on the App Service app. Users will not be prompted for login.
To make it secure I can enable App Service Authentication which will ask users to log in
But this is not what I want - The data in this app is only accessed by Application without the need of each and every user to login to my app before using it.
So you might say, in this case, Anonymous access is fine but I want to restrict it with something at least like an API Key so I will have access to the API which my app can use to access the data to prevent random requests as anyone can just go and use Postman and start getting data without any authentication.
So in short, I don't want individual user authentication, but at least an API Key to ensure only requests made from my app are authenticated and nothing else.
I am using the following in my mobile app to create a connection and also doing Offline sync etc
MobileServiceClient client = new MobileServiceClient(applicationURL);
Any idea how do I do that?
FYI. My server side backend is in C#
Since you are using Azure Mobile Apps, for your requirement, you could leverage Custom Authentication for building your CustomAuthController to login and generate the JWT token for a specific user without user interaction. The core code snippet for logging would look like as follow:
MobileServiceClient client = new MobileServiceClient("https://{your-mobileapp-name}.azurewebsites.net/");
client.LoginAsync("custom", JObject.FromObject(new{Username="***",Password="***"}));
Note: As the above tutorial mentions as follows:
You must turn on Authentication / Authorization in your App Service. Set the Action to take when request is not authenticated to Allow Request (no action) and do not configure any of the supported authentication providers.
And you must explicitly add [Authorize] attribute for your controllers / actions which need to be authorized access. Details you could follow Authentication in the Backend.

Azure web api authentication

I would like to secure my Azure WebApi with 3rd party providers (FB, G+... I basically just need a valid email). Was looking at Auth0 and seems like it will do the thing paired with Jwt middleware in web api project, but I was wondering if the same can be done using Azure only.
Azure Web App authentication confused me a bit - it does not seem to give anything to my Asp.Net web app. I still have to configure all the middleware in Startup.cs and the app still works fine if I completely turn authentication off.
I could do the same thing Auth0 does - issue my own Jwt tokens based on access tokens from FB or G+ - but would like to avoid that.
Could you please point me to the right direction?
You have a couple options:
App Service Authentication
Configure the authentication via middle ware
App Service Authentication
The App Service Authentication does not require any code inside your application because your App Service has a gateway that inspects request for authorization. Depending on the setting you can either secure the entire site or secure individual resources (by using the [Authorize] attribute on the endpoint in MVC/WebAPI).
With the latest release you can control authorization on a site by site basis including manually triggering the sign in by navigating the user to the <yoursiteurl>/.auth/login/<provider>. By defualt the token store is enabled so you can make a request to <yoursiteurl>/.auth/me and get back information from the provider.
Middleware Authentication
This is the default way authorization happens in the Single Page ASP.NET Template. The middleware authentication uses OAuth/OpenId to secure the resources. This option does it at the application layer instead of at the gateway. If you are using ASP.NET Identity (from the single page project template) the email from the persons log in will automatically be stored in the Users table. The tutorial in the link above gives lots of details on how to get it working.
Make sure you use the [Authorize] attribute to trigger the Authorization in either case.
Hope that helps you get started in the right direction.

Web API authentication and authorization (OAuth)

Consider the following (common) scenario. I will first try to specify how I understand a (nice) Web API should look like, using OAuth. Please do correct me if I got any of the flows wrong.
My API: the center of attention, all clients use this.
My Web App: Uses the API just like any other client would.
My Mobile App: Also uses the API, the same exact way as the web app. Users should be able to authenticate without opening a browser.
3rd party Web App: Also uses the API - however, the user/resource owner must grant permission for the app to do something. They do this by redirecting to my site (or opening a popup to it), logging the user in if necessary, and prompting the user for access.
3rd party Mobile App: Same requirements as the 3rd party web app.
The Question(s)
Should the API handle authentication and authorization?
How does the API know who (the resource owner that is using the client application), is using the API?
When a user is using my official clients, they should obviously not have to grant any permissions - my clients should have all permissions. How would I distinguish between my official clients, and 3rd party clients when calling the API?
Here is what I understand, and would do so far. This is where I really need help - getting this done right.
Official Web app
- Client attempts to `GET /api/tasks/".
- API says "who are you? (HTTP 401)
- Official web app redirects to login form.
> Bob enters his credentials.
- .. now what? Get an authentication token? Cookie?
Since the web app is just a consumer of my API, how would I manage the logged-in state? Should the web app do that?
Should the web app have direct access to the users database instead of verifying credentials against the API?
I am using .NET (C#) primarily, but I'd love an approach that is applicable to, say, Node JS based API's as well.
How would you go about this? Especially the client flows are a problem for me. The reason I ask, is that I have read that you should not roll your own security solution unless absolutely necessary, so if there are any standard-ish guidelines for this, do let me know. :)
Take a look at the new web API 2 oAuth stuff.
Basically fire up a new web API project and ensure you select to change the authentication.
Then, it's a simple case of calling the register controller. This then creates a token for you which can then be sent in the header of each request for that user.
Check out the API calls using fiddler and create some mock up accounts.
It's been awhile, but I thought I would document what I ended up doing.
I use DotNetOpenAuth. I have a database with clients, and they have a Trusted field - if this is set, it lets the client use the password grant, which automatically grants all scopes that have been predefined for that client.
The 1st-party web app uses plain cookie auth - exposing the client credentials in JS would be too risky.

Resources