如何解决Azure AD - 调用 Web API 的 WebForms Web 应用程序
我浏览了许多使用 asp.net 核心 Web 应用程序的示例,这些应用程序通过 AzureAD 调用受保护的 WebAPI。
我正在寻找一个很好的例子或者一些建议,以便在用 VB 编写的 WebForms 项目上工作。
我能够针对 WebClient 对用户进行身份验证,但是当我尝试使用 GetAccountAsync 或 GetAccountsAsync 方法调用 AcquiretokenSilent 时,我只会得到一个空帐户或一个空集合。
这是我在 WebForms 客户端的 Owin 启动中的代码:
Public Sub ConfigureAuth(ByVal app As IAppBuilder)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationoptions())
app.USEOpenIdConnectAuthentication(New OpenIdConnectAuthenticationoptions With {
.Authority = authority,.ClientId = clientId,.RedirectUri = redirectUri,.PostlogoutRedirectUri = postlogoutRedirectUri,.Scope = $"openid profile offline_access api://myapiID/defaultScope",.CookieManager = New SystemWebCookieManager(),.TokenValidationParameters = New Microsoft.IdentityModel.Tokens.TokenValidationParameters() With {
.ValidateIssuer = False,.NameClaimType = "name"
},.Notifications = New OpenIdConnectAuthenticationNotifications() With {
.AuthenticationFailed = AddressOf OnAuthenticationFailed,.AuthorizationCodeReceived = AddressOf OnAuthorizationCodeReceived
}
}
)
app.UseStageMarker(Pipelinestage.Authenticate)
End Sub
此时在 OnAuthorizationCodeReceived 事件中,我可以创建客户端并获取令牌。
Private Async Function OnAuthorizationCodeReceived(ByVal context As AuthorizationCodeReceivednotification) As Task
Try
Dim client As IConfidentialClientApplication = MsalAppBuilder.BuildConfidentialClientApplication(New ClaimsPrincipal(context.AuthenticationTicket.Identity))
Dim authResult As AuthenticationResult = Await client.AcquiretokenByAuthorizationCode(scopes,context.Code).ExecuteAsync()
Dim sToken As String = authResult.Accesstoken '//Here I get a token correctly
Catch ex As Exception
Throw New HttpRequestException($"Error: {ex.Message}")
End Try
End Function
当我尝试从应用程序的另一部分调用我的 API 时,我使用 AcquiretokenSilent 但它不起作用,因为我无法检索任何帐户。
代码如下:
Async Function GetTokenToCallApi(ByVal context As IOwinContext) As Task(Of String)
Dim scopes As IEnumerable(Of String) = {"api://MyApiId/DefaultScope"}
Try
Dim client As IConfidentialClientApplication = MsalAppBuilder.BuildConfidentialClientApplication()
'Dim account = Await client.GetAccountAsync(ClaimsPrincipal.Current.GetAccountId()) --> NULL
Dim account = Await client.GetAccountsAsync() --> EMPTY
Dim result As AuthenticationResult = Await client.AcquiretokenSilent(scopes,account.FirstOrDefault).ExecuteAsync().ConfigureAwait(False)
Return result.Accesstoken
Catch ex As Exception
Return ""
End Try
End Function
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。