10

I have an ASP.Net Web API 2 on which I implemented the following security: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-devquickstarts-webapi-dotnet

It worked, I can't access the controllers except if I remove the [Authorize] attribute.

Now, I have a logged in user in a Xamarin app. The user is logged in via MSAL authentication which works fine too. Very basic implementation :

var authenticationResult = await App.IdentityClientApp.AcquireTokenSilentAsync(App.ClientScope);
var token = authenticationResult.Token;

Now, I want to access the web API by giving the MSAL authentication token in the DefaultRequestHeaders with something like this :

this.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

Is there anyway this is possible ? How can I use this token to make my user consume my web API ?

Thank you !

4

1 回答 1

13

The tutorial Help protect a web API by using bearer tokens from Azure AD you mentioned targets on AD v1.0 and you need to register your apps on Azure Portal. While MSAL targets on AD v2.0 and you need to register your app at apps.dev.microsoft.com, and you need to use the middleware in your Web API 2 as follows:

var tvps = new TokenValidationParameters
{
    ValidAudience = clientId,
    ValidateIssuer = false,
};

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
    AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tvps, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"))
});

For more details, you could refer to active-directory-v2-devquickstarts-dotnet-api.

Additionally, you could refer to AppModelv2-WebAPI-DotNet for code samples about the web api backend and the mobile client via MSAL accessing the web api backend.

Update:

  • I downloaded the code sample AppModelv2-WebAPI-DotNet

  • Follow How to register an app with the v2.0 endpoint for registering my app for v2.0 as follows:

    enter image description here

  • Copy the Application Id from the above screenshot and update it to TodoListClient and TodoListService project as follows:

    enter image description here

  • Launch TodoListService first, then you could debug TodoListService as follows:

    enter image description here

Also, you could copy the Token and leverage postman to simulate the request as follows:

enter image description here

于 2017-06-08T02:38:37.763 回答