我尝试通过Azure AD应用程序角色创建受保护的控制器。
这是对Startup.Auth的免除,它基本上由Visual Studio模板提供:
public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
return Task.FromResult(0);
}
}
});
}
尝试过具有以下属性的ApiController:
[Authorize(Roles = "Administrators")]
// GET: api/Questions
[ResponseType(typeof(Question))]
public IHttpActionResult GetQuestions()
{
....
}
和MVC控制器:
[Authorize(Roles = "Administrators")]
public ActionResult Index()
{
....
}
在Azure应用程序清单中定义了以下内容:
"appRoles": [
{
"id": "B4531A9A-0DC8-4015-8CE5-CA1DA1D73754",
"allowedMemberTypes": ["User"],
"description": "Administrators",
"displayName": "Administrators",
"value": "Administrators",
"isEnabled": true,
"origin": "Application"
}
]
现在执行/ api / Questions的GET请求重定向到https://login.microsoftonline.com并且用户身份验证似乎成功,除了localhost和microsoft online之间存在无限循环请求。见下文:
我做错了什么?
使用[授权]工作正常。
答案 0 :(得分:8)
事实证明,应将以下内容添加到Startup.Auth:
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuer = true,
// map the claimsPrincipal's roles to the roles claim
RoleClaimType = "roles",
}
它实际上是配置“角色”声明类型,以便将其映射为默认行为。 有以下优秀说明: https://samlman.wordpress.com/2015/03/09/using-roles-in-azure-applications/
答案 1 :(得分:4)
对我来说,上面的解决方案不起作用。相反,我按照https://identityserver.github.io/Documentation/docs/overview/mvcGettingStarted.html中的说明实现了自定义AuthorizeAttribute
,以避免无限重定向循环。
以下是我的自定义AuthorizeAttribute
实现的代码(同样主要来自上面的资源):
public class RoleAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// If the user is authenticated, but we ended up here, it means that
// the user is not in a role that's allowed to use the controller being called
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
else
filterContext.Result = new HttpUnauthorizedResult();
}
}
PS:我不包含TokenValidationParameters
代码,我可以同时使用AuthorizeAttribute
指定的Roles
。但是,当我指定Authorize(Roles = "SomeRole")
并且已经过身份验证和授权的用户不在该角色中时,我面临无限重定向循环。
因此,对于那些必须使用基于角色的授权的控制器方法,我使用RoleAuthorize(Roles = "SomeRole")
代替。我还有一个自定义403错误页面,其样式与应用程序类似,并提供适当数量的详细信息和注销链接,以便用户可以尝试以其他用户身份进行身份验证。
我对该解决方案并不完全满意,因为我觉得内置的AuthorizeAttribute
应该能够处理这种情况。我只是无法让它发挥作用。
答案 2 :(得分:0)
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext.Request.Url.IsLoopback)
{
return true;
}
return base.AuthorizeCore(httpContext);
}
上面的代码旨在解除localhost调用。希望它适合你。