我编写了一个使用Azure AD的c#应用程序。下面是我的Startup.Auth.cs文件。当我连接到域时,一切正常。但是,当我在不在域上时使用User.IsInRole
时,我会收到信任关系错误。可能是什么原因?
此外:使用[Authorize(Roles="MyRole")]
作品!
确切的错误是:The trust relationship between this workstation and the primary domain failed.
// Startup.Auth.cs
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
private static string redirectUri = ConfigurationManager.AppSettings["ida:RedirectUri"];
string authority = aadInstance + tenantId;
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
RedirectUri = redirectUri,
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true, // For Single-Tenant App.
RoleClaimType = "roles" // Grab roles when user authenticates.
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
AuthenticationFailed = (context) =>
{
return System.Threading.Tasks.Task.FromResult(0);
}
}
});
// This makes any middleware defined above this line run before the Authorization rule is applied in web.config
app.UseStageMarker(PipelineStage.Authenticate);
}
答案 0 :(得分:0)
我终于弄明白了。这是我在控制器中做的一个例子:
var entitiesToDisplay = db.myEntities
.where(x => x.RequiredRole == string.empty || User.IsInRole(x.RequiredRole);
我将其更改为:
IEnumerable<Entities> entitiesToDisplay;
if (Request.IsAuthenticated) {
entitiesToDisplay = db.myEntities
.where(x => x.RequiredRole == string.empty || User.IsInRole(x.RequiredRole);
}
else {
entitiesToDisplay = new List();
}
最终,当User.IsInRole
不正确时,Request.IsAuthenticated
会抛出异常。检查Request.IsAuthenticated
解决了我的问题。