【问题标题】:In Web Api / Owin architecture, where are requests to '/token' handled?在 Web Api / Owin 架构中,对“/token”的请求在哪里处理?
【发布时间】:2014-06-06 14:18:55
【问题描述】:

我正在尝试了解 Asp.net Web Api 个人帐户身份验证和授权。我在网上看到了几个教程,包括this one。简而言之,当用户代理提供用户名和密码时,API 会发出一个令牌,客户端将在随后调用 API 时使用该令牌来识别自己。用户代理通过发出请求来接收令牌,通常发送到:http://example.com/Token。路径似乎是在 Startup 类中设置的,如下所示:

TokenEndpointPath = new PathString("/Token")

我的问题是,我找不到任何与该路径匹配的控制器方法。这是如何工作的?

【问题讨论】:

    标签: asp.net-web-api owin katana


    【解决方案1】:

    当您在 ASP.NET 中创建具有个人身份验证的新项目时,将使用 OAuth 提供程序创建解决方案以处理身份验证请求。

    如果您查看您的解决方案,您应该会看到一个带有 ApplicationOAuthProvider 类的 Providers 文件夹。

    这个类实现了在您的网站中验证您的成员的所有逻辑。 配置在启动时设置,允许您通过 OAuthOption 自定义 url 端点。

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };
    

    TokenEndPoint Path 属性定义了将触发 GrandResourceOwnerCredentials 的 GrantResourceOwnerCredentials 方法的 url。

    如果你使用fiddler来认证和使用这种body

     grant_type=password&username=testUserName&password=TestPassword
    

    你应该传入以下方法:

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
    
            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
    
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
    
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);
    
            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    

    其中 context.UserName 和 context.Password 使用请求中使用的数据进行设置。 确认身份后(此处使用实体框架和数据库中的一对用户名、密码),将不记名令牌发送给调用者。 然后可以使用此 Bearer 令牌对其他调用进行身份验证。

    问候。

    【讨论】:

    • @Jeremie,感谢您澄清这一点。真的很好的解释,这是我的确切问题。谁能告诉我使用这个默认的 oauth 不记名令牌是否是在 API 中实现安全性的最佳和最安全的方式?我正忙于开发一个 API,该 API 将暴露在互联网上并由我目前也在开发的 angularjs 移动应用程序使用。还有其他选择吗?非常感谢。
    • @Jeremie,是否可以有多个端点 url 都指向同一个 IAppBuilder 应用程序。如果不是,我们如何在一个 Web api 应用程序中拥有多个令牌端点?
    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2020-06-26
    • 2015-12-25
    • 1970-01-01
    • 2016-04-21
    • 2016-08-04
    • 2011-12-21
    相关资源
    最近更新 更多