使用Active Directory的Asp net core MVC授权

时间:2018-04-16 13:37:47

标签: active-directory asp.net-core-mvc roles active-directory-group asp.net-authorization

在Asp net core MVC应用程序中,我使用Active Directory进行自动登录,如下所示:

this.user = UserPrincipal.FindByIdentity(this.context, Environment.UserName);

我得到了用户的组:

public List<String> GetUserGroups()
{
   List<String> groups = new List<String>();
   foreach(GroupPrincipal gr in user.GetGroups())
   {
      groups.Add(gr.Name);
   }
   return groups;
}

我想与这些小组实施Autorisation,类似的东西:

[Authorize(Roles ="Admin")]
public IActionResult OnlyAdmin(){}

使用链接AD组和授权角色的东西,或者如果可能的话直接检查授权与AD组,但我不知道如何做这样的事情。

注意:我没有任何登录/退出页面,它只是自动的。

修改

不确切知道为什么或如何,但它最终无需任何代码工作,只有用户在PC中登录而不是this.user中指定的用户,但它很好。

但是现在我在尝试访问被拒绝的页面时遇到404错误,为什么它不是401或403错误?如何将拒绝访问重定向到自定义错误页面?

2 个答案:

答案 0 :(得分:0)

您需要在ClaimsPrincipal类中添加组,即

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, username));
foreach (string userGroup in authResponse)
{
    claims.Add(new Claim(ClaimTypes.Role, userGroup, ClaimValueTypes.String,"system","system"));
}

var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "authenticationScheme"));

现在在控制器或操作上使用authorize属性:

[Authorize(Roles = "guest,home")]

答案 1 :(得分:0)

您可以按如下方式编写ErrorHandlingMiddleware。您需要在启动文件中注册它

app.UseMiddleware(typeof(ErrorHandlingMiddleware));

以下是相同的例子。     公共类ErrorHandlingMiddleware     {         private readonly RequestDelegate _next;         私人只读ILogger _logger;

    public ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> createLogger)
    {
        this._next = next;
        this._logger = createLogger;
    }

    public async Task Invoke(HttpContext context)
    {
        var statusCode = HttpStatusCode.OK;

        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            this._logger.LogError(ex, ex.Message);
            switch (context.Response.StatusCode)
            {
                case (int)HttpStatusCode.NotFound:
                    statusCode = HttpStatusCode.NotFound;
                    break;
                case (int)HttpStatusCode.Forbidden:
                    statusCode = HttpStatusCode.Forbidden;
                    break;
                case (int)HttpStatusCode.BadRequest:
                    statusCode = HttpStatusCode.BadRequest;
                    break;
                default:
                    statusCode = HttpStatusCode.InternalServerError;
                    break;
            }

            context.Response.StatusCode = (int)statusCode;
        }

        if (!context.Response.HasStarted)
        {
            context.Response.ContentType = "application/json";

            var response = new { code = statusCode };

            var json = JsonConvert.SerializeObject(response);

            await context.Response.WriteAsync(json);
        }
    }
}