【问题标题】:ASP.net 5 Web API 2 Password AuthenticationASP.net 5 Web API 2 密码验证
【发布时间】:2015-11-01 23:45:30
【问题描述】:

我想要一个非常简单的 ASP.net 5 身份验证

您需要验证的只是一个密码。没有 UserManager 或任何类似的东西。

登录操作看起来如何,或者我必须如何继续实现?

编辑: 密码是全局密码,不是每个用户的密码。

【问题讨论】:

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


    【解决方案1】:

    我没有对此进行测试,所以这只是一个起点。 你需要实现一个自定义的 AuthenticationHandler。

    类似:

    class PasswordAuthenticationHandler : AuthenticationHandler<PasswordAuthenticationOptions>
    {
        public PasswordAuthenticationHandler (PasswordAuthenticationOptionsoptions)
        {
            //set fields needed from options        
        }
    
        protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
        {
            //get the password out of the Request and create claims collection
            ...
            var claimsId = new ClaimsIdentity(claims, Options.AuthenticationType);
            return new AuthenticationTicket(claimsId, new AuthenticationProperties());// can use AuthenticationProperties to set additional propertiues needed in ticket
        }
    
        // override ApplyResponseChallengeAsync
    
     }
    

    创建从 AuthenticationOptions 继承的 PasswordAuthenticationOptions。

    创建 OWIN 中间件

    public class PasswordAuthenticationMiddleware : AuthenticationMiddleware<PasswordAuthenticationOptions>
    {
        public delegate Task<IEnumerable<Claim>> CredentialValidationFunction(string id, string secret);
    
        public PasswordAuthenticationMiddleware(OwinMiddleware next, PasswordAuthenticationOptions options)
            : base(next, options)
        {}
    
        protected override AuthenticationHandler<PasswordAuthenticationOptions> CreateHandler()
        {
            return new PasswordAuthenticationHandler(Options);
        }
    }
    

    然后在 Startup.cs 中你会像这样使用它:

    app.Use<PasswordAuthenticationMiddleware>(options);
    

    您应该能够使用类、方法上的 Authorize 属性或将其添加为全局过滤器来锁定事物。

    我建议您查看:
    http://leastprivilege.com/2015/10/12/the-state-of-security-in-asp-net-5-and-mvc-6-authorization/
    https://github.com/leastprivilege/AspNet5AuthorizationPlayground/tree/master/src/Authentication

    【讨论】:

      【解决方案2】:

      你可以尝试实现最简单的方法:

      1. 在 api 控制器的操作中检查密码。
      2. 设置一些生成的或预定义的 cookie 或使用令牌返回响应。
      3. 创建自定义 ActionFilter 并检查您的 cookie 或令牌(在查询字符串或 http 请求标头内)是否有 Authorization

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-20
        • 2017-02-21
        • 2023-04-08
        • 2017-11-27
        • 2016-06-09
        • 1970-01-01
        • 2016-07-17
        • 2015-01-12
        相关资源
        最近更新 更多