Use MSAL Auth token to consume Web API 2

偶尔善良 提交于 2019-12-09 17:48:55

问题


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 !


回答1:


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:

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

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

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



来源:https://stackoverflow.com/questions/44413587/use-msal-auth-token-to-consume-web-api-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!