微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-web-api – 在Web Api / Owin架构中,处理“/ token”的请求在哪里?

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

我的问题是,我找不到与该路径匹配的任何控制器方法.这个怎么用?

解决方法

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

如果你看看你的解决方案,你应该看到一个Providers文件夹与一个ApplicationOAuthProvider类.

该类实现了在您的网站上验证您的会员的所有逻辑.
配置在启动时设置为允许您通过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.

如果您使用提琴手认证并使用这种身体

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与请求中使用的数据一起设置.
身份确认后(这里使用实体框架和一对用户名,数据库中的密码),承载令牌将发送给呼叫者.
然后可以将此承载令牌用于对其他呼叫进行身份验证.

问候.

原文地址:https://www.jb51.cc/aspnet/249870.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐