C# 如何使用标识v2从Startup.Auth.cs公开/Token端点

C# 如何使用标识v2从Startup.Auth.cs公开/Token端点,c#,asp.net-identity-2,C#,Asp.net Identity 2,我正在使用ASP.NET Identity 2并尝试启用令牌身份验证。从Identity 2示例中,没有关于令牌身份验证的内容,因此我通过查看不同的帖子来设置自己。我正在关注这篇文章的最后一个答案 并且能够设置每一项和所有内容,但现在当我试图在浏览器http://localhost:6722/token获取404错误。有什么想法吗 更新: 这是我的ApplicationAuthProvider.cs public class ApplicationOAuthProvider<TUserMa

我正在使用ASP.NET Identity 2并尝试启用令牌身份验证。从Identity 2示例中,没有关于令牌身份验证的内容,因此我通过查看不同的帖子来设置自己。我正在关注这篇文章的最后一个答案

并且能够设置每一项和所有内容,但现在当我试图在浏览器
http://localhost:6722/token
获取404错误。有什么想法吗

更新:

这是我的ApplicationAuthProvider.cs

public class ApplicationOAuthProvider<TUserManager, TUser, TKey> : OAuthAuthorizationServerProvider
        where TUserManager : UserManager<TUser, TKey>
        where TUser : class, IUser<TKey>
        where TKey : IEquatable<TKey>
    {
        private readonly string _publicClientId;


        public ApplicationOAuthProvider(string publicClientId)
        {
            if (publicClientId == null)
            {
                throw new ArgumentNullException("publicClientId");
            }


            _publicClientId = publicClientId;
        }

        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.Get<TUserManager>(_publicClientId);

            TUser 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 userManager.CreateIdentityAsync(user,
            context.Options.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
            CookieAuthenticationDefaults.AuthenticationType);
            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }

        public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            // Resource owner password credentials does not provide a client ID.
            if (context.ClientId == null)
            {
                context.Validated();
            }

            return Task.FromResult<object>(null);
        }

        public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
        {
            if (context.ClientId == _publicClientId)
            {
                Uri expectedRootUri = new Uri(context.Request.Uri, "/");

                if (expectedRootUri.AbsoluteUri == context.RedirectUri)
                {
                    context.Validated();
                }
            }

            return Task.FromResult<object>(null);
        }

        public static AuthenticationProperties CreateProperties(string userName)
        {
            IDictionary<string, string> data = new Dictionary<string, string>
            {
                {
                    "userName", userName
                }
            };
            return new AuthenticationProperties(data);
        }
    }
公共类ApplicationAuthProvider:OAuthAuthorizationServerProvider
其中TUserManager:UserManager
托瑟:上课,尤瑟
其中TKey:IEquatable
{
私有只读字符串_publicClientId;
公共ApplicationAuthProvider(字符串publicClientId)
{
if(publicClientId==null)
{
抛出新ArgumentNullException(“publicClientId”);
}
_publicClientId=publicClientId;
}
公共重写异步任务GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentials上下文)
{
var userManager=context.OwinContext.Get(_publicClientId);
TUser user=await userManager.FindAsync(context.UserName,context.Password);
if(user==null)
{
SetError(“无效的授权”,“用户名或密码不正确”);
返回;
}
ClaimsIdentity oAuthIdentity=等待userManager.CreateIdentityAsync(用户,
context.Options.AuthenticationType);
ClaimsIdentity cookiesIdentity=await userManager.CreateIdentityAsync(用户,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties=CreateProperties(user.UserName);
AuthenticationTicket=新的AuthenticationTicket(OAuthidentitity,属性);
上下文。已验证(票证);
context.Request.context.Authentication.sign(cookiesIdentity);
}
公共重写任务令牌端点(OAuthTokenEndpointContext)
{
foreach(context.Properties.Dictionary中的KeyValuePair属性)
{
AdditionalResponseParameters.Add(property.Key,property.Value);
}
返回Task.FromResult(空);
}
公共覆盖任务ValidateClientAuthentication(OAuthValidateClientAuthenticationContext)
{
//资源所有者密码凭据不提供客户端ID。
if(context.ClientId==null)
{
context.Validated();
}
返回Task.FromResult(空);
}
公共覆盖任务ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext上下文)
{
if(context.ClientId==\u publicClientId)
{
Uri expectedRootUri=新Uri(context.Request.Uri,“/”;
if(expectedRootUri.AbsoluteUri==context.RedirectUri)
{
context.Validated();
}
}
返回Task.FromResult(空);
}
公共静态身份验证属性CreateProperties(字符串用户名)
{
IDictionary data=新字典
{
{
“用户名”,用户名
}
};
返回新的AuthenticationProperties(数据);
}
}
这是我的Startup.Oauth.cs

 public partial class Startup
    {

        static Startup()
        {
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider<ApplicationUserManager, User, int>(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = false
            };

        }
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
        public static string PublicClientId { get; private set; }


        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and role manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDb.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User, int>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (claim) => int.Parse(claim.GetUserId()))

                }
            });



            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);



            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication();
        }
    }
公共部分类启动
{
静态启动()
{
PublicClientId=“self”;
OAuthOptions=新的OAuthAuthorizationServerOptions
{
TokenEndpointPath=新路径字符串(“/Token”),
Provider=新的ApplicationAuthProvider(PublicClientId),
AuthorizeEndpointPath=新路径字符串(“/api/Account/ExternalLogin”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(14),
AllowInsecureHttp=false
};
}
公共静态OAuthAuthorizationServerOptions OAuthOptions{get;private set;}
公共静态字符串PublicClientId{get;private set;}
//有关配置身份验证的详细信息,请访问http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder应用程序)
{
//将数据库上下文、用户管理器和角色管理器配置为每个请求使用一个实例
app.CreatePerOwinContext(ApplicationDb.Create);
app.CreatePerOwinContext(ApplicationUserManager.Create);
app.CreatePerOwinContext(ApplicationRoleManager.Create);
//使应用程序能够使用cookie存储登录用户的信息
//以及使用cookie临时存储用户登录第三方登录提供商的信息
//配置登录cookie
app.UseCookieAuthentication(新的CookieAuthenticationOptions
{
AuthenticationType=DefaultAuthenticationTypes.ApplicationOkie,
LoginPath=新路径字符串(“/Account/Login”),
Provider=新CookieAuthenticationProvider
{
//允许应用程序在用户登录时验证安全戳。
//这是一种安全功能,在您更改密码或向帐户添加外部登录时使用。
OnValidateIdentity=SecurityStampValidator.OnValidateIdentity(
validateInterval:TimeSpan.FromMinutes(30),
regenerateIdentityCallback:(管理器,用户)=>user.GenerateUserIdentityAsync(管理器),
getUserIdCallback:(claim)=>int.Parse(claim.GetUserId())
}
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(YOUR_NAME_SPACE_TO_THE_STARTUP_FILE.Startup))]
namespace YOUR_NAME_SPACE_TO_THE_STARTUP_FILE
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}
{
    error: "unsupported_grant_type"
}