简体   繁体   English

没有OWIN和AspNet.Identity的基于Asp.Net Web Api令牌的授权

[英]Asp.Net Web Api Token Based Authorization WITHOUT OWIN and AspNet.Identity

I am planning to use the codes below for my web api security but i am not sure that is enough safe and logical way. 我正计划将以下代码用于Web api安全性,但是我不确定这是否足够安全且合乎逻辑。 I don't want to use OWIN and AspNet.Identity because it's very complicated for me and i don't understand completely and I don't know how i customize db tables, user roles etc. But my way is simple and very customizable for me. 我不想使用OWIN和AspNet.Identity,因为它对我来说非常复杂,我也不完全了解,也不知道如何自定义数据库表,用户角色等。我。

This is CustomAuthorizeAttribute; 这是CustomAuthorizeAttribute;

public class CustomAuthorize : AuthorizeAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if ((actionContext.Request.Headers.GetValues("Host").FirstOrDefault().Contains("localhost:15742")))
        {
            IEnumerable<string> access_token;
            if (actionContext.Request.Headers.TryGetValues("Authorization", out access_token))
            {
                var user = GetUserByToken(access_token);
                if (user!=null && !user.TokenIsExpired)
                {
                    HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Custom " + access_token.FirstOrDefault());
                    return;
                }
                else
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
                    HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Custom");
                    return;
                }
            }
            else
            {
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            }
        }
        else
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
        }
    }
}

And this is front end using 这是前端使用

<script type="text/javascript">
    $(function () {
        var access_token = $.cookie('access_token');
        if (access_token == undefined) {
            $.cookie('access_token', 'test-token');
        }


        $.ajax({
            url: '/api/account',
            headers: { access_token: access_token },
            success: function (data) {
                document.write(data.name + " " + data.lastname);
            }
        });
    });
</script>

By the way i am sorry about for my English. 顺便说一句,我为我的英语感到抱歉。 I hope you understand my problem and i am waiting for your suggestions. 希望您理解我的问题,我正在等待您的建议。

Necroreply for ones who looking to make custom auth attributes :) 对那些希望创建自定义身份验证属性的人进行死灵回复:)

First check is redundant, since HTTP request is just a string of text over TCP connection so anyone can connect to your server with TCP client and send whatever header he wants. 第一次检查是多余的,因为HTTP请求只是TCP连接上的文本字符串,因此任何人都可以使用TCP客户端连接到您的服务器并发送他想要的任何标头。 actionContext.Request.Headers.GetValues("Host").FirstOrDefault().Contains("localhost:15742"))

According to https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api 根据https://docs.microsoft.com/zh-CN/aspnet/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

Authorization filters run before the controller action. 授权过滤器在控制器操作之前运行。 If the request is not authorized, the filter returns an error response, and the action is not invoked. 如果请求未被授权,则过滤器将返回错误响应,并且不会调用该操作。

the only way you attribute does not set Response is user!=null && !user.TokenIsExpired so this attribute will do the job and can be considered secure. 您的属性未设置“ Response”的唯一方法是user!=null && !user.TokenIsExpired因此此属性将user!=null && !user.TokenIsExpired ,并且可以认为是安全的。

This header can be removed HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Custom"); 可以删除此标头HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Custom");

Also why would you send auth token again in case of success? 另外,如果成功,为什么还要再次发送身份验证令牌? HttpContext.Current.Response.AddHeader("WWW-Authenticate", "Custom " + access_token.FirstOrDefault());

Just reduce IF-s nesting level so the code will be easier to read: 只需降低IF-s的嵌套级别,即可使代码更易于阅读:

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        IEnumerable<string> access_token;

        if (!actionContext.Request.Headers.TryGetValues("Authorization", out access_token))
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            return;
        }

        var user = GetUserByToken(access_token);

        if (user == null || user.TokenIsExpired)
        {
            actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);                
            return;
        }

        // OK
        return;
    }

A lot of ASP.NET code is seems overengineered (and sometimes is :) including OWIN. 包括OWIN在内的许多ASP.NET代码似乎都经过了过度设计(有时是:)。 But it has a purpose – to declare a standard way of doing variuos things, like auth for example. 但这有一个目的–声明一种做杂事的标准方法,例如auth。

Imagine everyone will start building their custom attrbiutes, then it will be impossible to just install Google nuget package and do something like 假设每个人都将开始构建自定义属性,那么就不可能仅安装Google nuget软件包并执行类似的操作

public void ConfigureAuth(IAppBuilder app)
{
     app.UseGoogleAuthentication(
         clientId: "000-000.apps.googleusercontent.com",
         clientSecret: "00000000000");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将ASP.NET Core WEB API令牌身份验证与OWIN / Katana OAuth 2.0授权服务器一起用作资源服务器 - Use ASP.NET Core WEB API token authentication as a resourceserver with OWIN/Katana OAuth 2.0 Authorization Server OWIN ASP.NET - 避免在Web Api中没有Identity的同一帐户进行多次登录 - OWIN ASP.NET - Avoid multiple logins for the same account without Identity in Web Api IdentityServer4 基于角色的 Web API 授权与 ASP.NET Core 标识 - IdentityServer4 Role Based Authorization for Web API with ASP.NET Core Identity Asp.Net Web API - Asp.Net Identity和Owin vs HttpModule AuthenticateRequest - Asp.Net Web API - Asp.Net Identity and Owin vs HttpModule AuthenticateRequest 使用ASP.NET Identity和Autofac OWIN集成进行授权 - Authorization with ASP.NET Identity & Autofac OWIN integration 授权错误 - 具有基于令牌的授权和角色的ASP.NET Web API - Authorize Error - ASP.NET Web API with Token based authorization and Roles 在ASP.NET OWIN OpenIdConnect代码授权流程中通过基于令牌的身份验证替换Cookie - Replacing Cookie by Token based authentication in ASP.NET OWIN OpenIdConnect code authorization flow 电子邮件确认ASP.NET Identity 2 OWIN MVC和API无效令牌 - Email Confirmation ASP.NET Identity 2 OWIN MVC and API Invalid Token Asp.Net Identity RTM版本中的Microsoft.AspNet.Identity.Owin.AuthenticationManager在哪里? - Where is Microsoft.AspNet.Identity.Owin.AuthenticationManager in Asp.Net Identity RTM version? Asp.net OWIN身份刷新令牌和令牌过期 - Asp.net OWIN Identity refresh tokens and token expiration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM