如何在Net Core Web API中覆盖OnAuthorization? [英] How do I override OnAuthorization in net core web api?

查看:321
本文介绍了如何在Net Core Web API中覆盖OnAuthorization?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早些时候,我在asp.net中实现了类似的目标

Earlier I achieved something like this in 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}

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

Now this doesn't seem to work in net core, the goal is to read the Authorization header and de-serialize it so i can pass it to my database logic that goes something like this

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中,我有类似的东西

Then in my ValuesController i had something as such

[Authentication]
 public HttpResponseMessage Get()
    {

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

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

Now this code might be ugly but I hope it makes sense enough for readers to understand what I want to achieve.

此操作的基本思想是它将成为我的桌面应用程序仅与MySql数据库进行通信的API.让我知道是否应该澄清一下!

The base idea for this is that it will be an API for my desktop app to communicate with a MySql database only. Let me know if I should clarify something!

另外一个问题,当使用netcore时,我似乎根本无法使IntelliSense正常工作,是否可以启用此功能,或者因为它是beta版本而缺乏?

Extra question, i can't seem to make IntelliSense work at all when using netcore is there a way to enable this or is it lacking because it's beta?

推荐答案

您可以使用自定义中间件作为MVC筛选器来完成此任务.这是在 ASP中宣布的.NET Core 1.1 (请参阅有关作为MVC筛选器的中间件的部分).

You can use custom middleware as an MVC filter to accomplish this. This was announced in ASP.NET Core 1.1 (see the section on Middleware as MVC filters).

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

Here is some example code based on your example:

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

First, create your custom middleware to do the work:

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>();
    }
}

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

Then, create the pipeline class to use the middleware:

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

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

Finally, on your action method, add the filter:

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

这篇关于如何在Net Core Web API中覆盖OnAuthorization?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆