如何使用Identity v2从Startup.Auth.cs公开/令牌端点
本文关键字:公开 cs 令牌 端点 Auth Startup 何使用 Identity v2 | 更新日期: 2023-09-27 18:03:17
我正在与ASP合作。NET Identity 2并尝试启用令牌身份验证。从Identity 2示例中没有关于令牌身份验证的内容,所以我通过查看不同的帖子来设置自己。我跟随这篇文章的最后一个答案。NET Identity 2.0's DbContext中间件?
并能够设置每一个和一切,但现在当我试图达到这个终点在浏览器http://localhost:6722/token
得到404错误。任何想法?
这是我的ApplicationOAuthProvider.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);
}
}
这是我的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();
}
}
和我试图访问/令牌结束点直接从浏览器,它抛出404错误。
我今天遇到了类似的问题,为我解决问题的是安装以下Nuget包。
我不知道为什么它没有和其他所有的包一起安装,但是试一试,让我们知道。
包名是Microsoft.Owin.Host.SystemWeb
你有启动类的其他部分吗?因为在你的web项目中应该有一个Startup.cs文件,它正在调用你的ConfigureAuth方法。如果不是,您将得到404异常。startup.cs文件应该如下所示:
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"
}
在我的案例中,我将AllowInsecureHttp
封装在#if DEBUG
处理器指令中,并最终将其发布到服务器(作为Release),而我的客户没有负担SSL。
在删除DEBUG
条件后,现在一切正常。
我刚刚有一个类似的(如果不相同)问题,我在访问/token
时得到404。最终我发现,这是由于我在启动时调用东西的顺序。配置方法。我在这个方法的最底部调用ConfigureAuth(app)
,在我添加了Ninject配置(即。app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config);
。将ConfigureAuth
移动到Ninject设置的上方修复了这个问题,/token
现在可以工作了。