我有一个使用Azure AAD授权的asp.net mvc应用程序。该应用程序是基于此github上例如:asp.net上的自定义授权属性mvc
https://github.com/dushyantgill/VipSwapper/tree/master/TrainingPoint
这个程序有一个自定义属性授权
public class AuthorizeUserAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext ctx)
{
if (!ctx.HttpContext.User.Identity.IsAuthenticated)
base.HandleUnauthorizedRequest(ctx);
else
{
ctx.Result = new ViewResult { ViewName = "Error", ViewBag = { message = "Unauthorized." } };
ctx.HttpContext.Response.StatusCode = 403;
}
}
}
然而,这似乎很奇怪我。
我有一个控制器是这样的:
public class GlobalAdminController : Controller
{
// GET: GlobalAdmin
[AuthorizeUser(Roles = "admin")]
public ActionResult Index()
{
return View();
}
}
正如你可以看到自定义属性是用来那里,而是采取在自定义属性的代码更深入的了解。 显然,在if和else两个请求都没有通过认证。
现在看看这个截图。
没有意义吗? http://screencast.com/t/obqXHZJj0iNG
问题是,我应该怎么做才能让用户执行控制器?
更新1: 在我的身份验证流程,我有以下
public void ConfigureAuth(IAppBuilder app)
{
// configure the authentication type & settings
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
// configure the OWIN OpenId Connect options
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = SettingsHelper.ClientId,
Authority = SettingsHelper.AzureADAuthority,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// when an auth code is received...
AuthorizationCodeReceived = (context) => {
// get the OpenID Connect code passed from Azure AD on successful auth
string code = context.Code;
// create the app credentials & get reference to the user
ClientCredential creds = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
string userObjectId = context.AuthenticationTicket.Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
// use the ADAL to obtain access token & refresh token...
// save those in a persistent store...
EfAdalTokenCache sampleCache = new EfAdalTokenCache(userObjectId);
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, sampleCache);
// obtain access token for the AzureAD graph
Uri redirectUri = new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path));
AuthenticationResult authResult = authContext.AcquireTokenByAuthorizationCode(code, redirectUri, creds, SettingsHelper.AzureAdGraphResourceId);
if (GraphUtil.IsUserAADAdmin(context.AuthenticationTicket.Identity))
context.AuthenticationTicket.Identity.AddClaim(new Claim("roles", "admin"));
// successful auth
return Task.FromResult(0);
},
AuthenticationFailed = (context) => {
context.HandleResponse();
return Task.FromResult(0);
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = false
}
});
}
检查特地IsAADAdmin方法调用
/// <summary>
/// The global administrators and user account administrators of the directory are automatically assgined the admin role in the application.
/// This method determines whether the user is a member of the global administrator or user account administrator directory role.
/// RoleTemplateId of Global Administrator role = 62e90394-69f5-4237-9190-012177145e10
/// RoleTemplateId of User Account Administrator role = fe930be7-5e62-47db-91af-98c3a49a38b1
/// </summary>
/// <param name="objectId">The objectId of user or group that currently has access.</param>
/// <returns>String containing the display string for the user or group.</returns>
public static bool IsUserAADAdmin(ClaimsIdentity Identity)
{
string tenantId = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string signedInUserID = Identity.FindFirst(System.IdentityModel.Claims.ClaimTypes.NameIdentifier).Value;
string userObjectID = Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
ClientCredential credential = new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthority, new EfAdalTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenSilent(
SettingsHelper.AzureAdGraphResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
HttpClient client = new HttpClient();
string doQueryUrl = string.Format("{0}/{1}/users/{2}/memberOf?api-version={3}",
SettingsHelper.AzureAdGraphResourceId, tenantId,
userObjectID, SettingsHelper.GraphAPIVersion);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, doQueryUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = client.SendAsync(request).Result;
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
string responseString = responseContent.ReadAsStringAsync().Result;
var memberOfObjects = (System.Web.Helpers.Json.Decode(responseString)).value;
if (memberOfObjects != null)
foreach (var memberOfObject in memberOfObjects)
if (memberOfObject.objectType == "Role" && (
memberOfObject.roleTemplateId.Equals("62e90394-69f5-4237-9190-012177145e10", StringComparison.InvariantCultureIgnoreCase) ||
memberOfObject.roleTemplateId.Equals("fe930be7-5e62-47db-91af-98c3a49a38b1", StringComparison.InvariantCultureIgnoreCase)))
return true;
}
return false;
}
我100%肯定的用户是在管理作用,因为当我调试它返回true和声明创建
更新2: 在调试我检查了User.Claims和角色admin在那里。 所以我不知道每个角色本授权如何与User.IsInRole
http://screencast.com/t/zUbwbpzn55qb
您发布的代码只在用户未被授权时被调用,否则它使用AuthorizeAttribute的默认行为。所以我不明白你的问题是什么。 –
身份验证和授权是两个不同的事情。用户可能登录但不是管理员,因此他已通过身份验证但未获得授权。您需要将该用户作为管理员添加到“webpages_UsersInRoles”表中以供他授权。 –
我确信用户已经通过身份验证,并且它在角色admin中,请参阅Update1,代码来自我提供的示例代码,但我也将其粘贴到此处以提供更多解释 –