在Web Api/Owin架构中,处理'/ token'的请求在哪里?

Joe*_*Joe 24 asp.net-web-api owin katana

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

TokenEndpointPath = new PathString("/Token")
Run Code Online (Sandbox Code Playgroud)

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

Jer*_*ard 31

在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
};
Run Code Online (Sandbox Code Playgroud)

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

如果你使用fiddler进行身份验证并使用这种身体

 grant_type=password&username=testUserName&password=TestPassword
Run Code Online (Sandbox Code Playgroud)

你应该传递以下方法:

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);
    }
Run Code Online (Sandbox Code Playgroud)

其中context.UserName和context.Password是使用请求中使用的数据设置的.身份被确认后(这里使用实体框架和一对夫妇的用户名,密码在数据库中),承载令牌发送给调用者.然后可以使用该承载令牌对其他呼叫进行认证.

问候.