【问题标题】:How do I override OnAuthorization in net core web api?如何在 net core web api 中覆盖 OnAuthorization?
【发布时间】:2017-01-10 11:44:54
【问题描述】:

之前我在 asp.net 中实现了类似的功能

public class Authentication : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.Headers.Authorization == null)
        {
            actionContext.Response = actionContext.Request
                .CreateResponse(HttpStatusCode.Unauthorized);
        } else
        {
            var authenticationToken = actionContext.Request.Headers
                .Authorization.Parameter;
            var decodedAuthenticationToken = Encoding.UTF8.GetString(
                Convert.FromBase64String(authenticationToken));
            var usernamePasswordArray = decodedAuthenticationToken.Split(':');
            var username = usernamePasswordArray[0];
            var password = usernamePasswordArray[1];

            if (GetUsers.GetDatabaseUsers.CheckCredentials(username, password))
            {// logic}

现在这似乎在网络核心中不起作用,目标是读取授权标头并将其反序列化,以便我可以将其传递给我的数据库逻辑,类似于这样

public static bool CheckCredentials(string username, string password)
        {
            try
            {
                var databaseConnection = new MySqlConnection(ConnectionString);
                var queryCommand =
                    new MySqlCommand(
                        "SELECT COUNT(*) FROM users WHERE username LIKE @username AND password LIKE @password",
                        databaseConnection);// more code

然后在我的 ValuesController 我有这样的东西

[Authentication]
 public HttpResponseMessage Get()
    {

        var returnData = string.Format("database model logic{0}",mydatabasehandler.sologic,
        return Request.CreateResponse(HttpStatusCode.OK, returnData);
    }

现在这段代码可能很难看,但我希望它足够有意义,让读者理解我想要实现的目标。

这样做的基本想法是,它将成为我的桌面应用程序的 API,仅与 MySql 数据库进行通信。让我知道是否需要澄清一些事情!

另外一个问题,我似乎在使用 netcore 时根本无法让 IntelliSense 工作。有没有办法启用它,还是因为它是测试版而缺少它?

【问题讨论】:

  • 对于您的额外问题,请确保您使用的是所有内容的最新版本。我对智能感知没有任何问题。以下是我正在运行的版本:Visual Studio Enterprise 2015 Update 3 (14.0.25431.01 Update 3),Microsoft .NET Core Tools (extensions): 14.1.21111.0,在命令行运行“dotnet”,它是 1.1。 0,并且“dotnet --version”返回 1.0.0-preview2-1-003177
  • 作为建议,更好的方法是从中创建身份验证中间件。它可以基于 headers 创建一个 ClaimsPrincipal,授权可以基于该 headers。在 ASP.NET Core 中,建议制作自定义 AuthorizationAttribute。
  • 另外,关于您的智能感知问题,如果您运行的是 ReSharper v10.x,您可能需要升级到支持 .net 核心的最新版本。

标签: c# asp.net-core asp.net-web-api


【解决方案1】:

您可以使用自定义中间件作为 MVC 过滤器来完成此操作。 这是在ASP.NET Core 1.1 中宣布的(请参阅中间件作为 MVC 过滤器的部分)。

这是基于您的示例的一些示例代码:

首先,创建您的自定义中间件来完成这项工作:

public class MyCustomAuthenticationMiddleware
{
    private readonly RequestDelegate next;

    public MyCustomAuthenticationMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        string authoriztionHeader = context.Request.Headers["Authorization"];

        if (authoriztionHeader != null && authoriztionHeader.StartsWith("Basic"))
        {
            var encodedUsernamePassword = authoriztionHeader.Substring("Basic ".Length).Trim();
            var encoding = Encoding.GetEncoding("iso-8859-1");
            var usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
            var seperatorIndex = usernamePassword.IndexOf(':');
            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            if (GetUsers.GetDatabaseUsers.CheckCredentials(username, password))
            {
                // your additional logic here...

                await this.next.Invoke(context);
            }
            else
            {
                context.Response.StatusCode = 401;
            }
        }
        else
        {
            context.Response.StatusCode = 401;
        }
    }
}

public static class MyCustomAuthenticationMiddlewareExtensions
{
    public static IApplicationBuilder UseMyCustomAuthentication(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyCustomAuthenticationMiddleware>();
    }
}

然后,创建管道类以使用中间件:

public class MyCustomAuthenticationMiddlewarePipeline
{
    public void Configure(IApplicationBuilder app)
    {
        app.UseMyCustomAuthentication();
    }
}

最后,在您的操作方法上,添加过滤器:

[MiddlewareFilter(typeof(MyCustomAuthenticationMiddlewarePipeline))]
public HttpResponseMessage Get()
{
    var returnData = DoSomeWork();
    return this.Request.CreateResponse(HttpStatusCode.OK, returnData);
}

【讨论】:

  • 非常感谢,现在我有一个基础可以更好地理解它,然后我可以使用 msdn 文档。
猜你喜欢
  • 1970-01-01
  • 2019-08-28
  • 2021-12-11
  • 1970-01-01
  • 2011-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-08
相关资源
最近更新 更多