-->

How to add simple authentication to azure mobile/w

2020-08-04 04:10发布

问题:

My goal is to secure my mobile app custom API methods and use then via httpclient(c#).

As a part of the testing I used Postman to request a token and use it to access the resource.

回答1:

I will explain with the vanilla template that comes when creating a new Mobile App.

  1. Create a new mobile app.

  2. Publish it to Azure.

  3. Open it on Azure portal, Go to Settings blade. Find Authentication / Authorization.

  4. Turn App Service Authentication to On and select Azure Active Directory>Express>Create a new AD app.

  5. Open Active Directory (Management Portal), pick the directory for your account.

  6. Select Applications, the one you just created.

  7. Go to Configure tab and copy the ClientId, Create a Key, copy it too.

  8. Click on View EndPoints at the bottom and copy the OAuth 2.0 Token EndpointOauth2.0 Token

  9. Now open the mobile app project and decorate the controller/method you want to project with [Authorize].

You should be all set with the setup.

Now open your favorite client, in my case Postman and

Step 1: Request a token

Method: POST
URL : {Oauth TokenEndPoint from Step. 8}
grant_type : client_credentials
client_id : {one copied from AD section in Step. 7}
client_secret : {one copied from AD section in Step. 7}
resource : {one copied from AD section in Step. 7}

You will receive a response like this

  "token_type": "Bearer",
  "expires_in": "3600",
  "expires_on": "1453151213",
  "not_before": "1453147313",
  "resource": "yyyyyyyyyyyyyyyyyy",
  "access_token": "xxxxxxxxxxxxxxxxxxx"

Now copy the access_token and use it in your request to the mobile app.

   Method: Get
    URL : https://MyMobileApp.azurewebsites.net/api/values?ZUMO-API-VERSION=2.0.0
   Headers : Authorization : Bearer xxxxxxxxxxxxxxxxxxx

In case if you run into any issues, here is a key step. Go to Azure portal and turn on Application Logging, Detailed error messages, Failed request tracking under Diagnostics logs (Settings blade).

Now you can see whats happening and much more detailed logging under Log Stream(Tools blade).