OpenIddict – 如何获取用户的访问令牌?

我正在使用AngularJs为OpenIddict开发示例应用程序。 我被告知你不应该使用像Satellizer这样的客户端框架,因为这不是建议的,而是允许服务器处理服务器端的登录(本地和使用外部登录提供程序),并返回访问令牌。

我有一个演示angularJs应用程序并使用服务器端登录逻辑并回调角度应用程序,但我的问题是,我如何获得当前用户的访问令牌?

这是我的startup.cs文件,所以到目前为止你可以看到我的配置

public void ConfigureServices(IServiceCollection services) { var configuration = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables() .Build(); services.AddMvc(); services.AddEntityFramework() .AddSqlServer() .AddDbContext(options => options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"])); services.AddIdentity() .AddEntityFrameworkStores() .AddDefaultTokenProviders() .AddOpenIddict(); services.AddTransient(); services.AddTransient(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { env.EnvironmentName = "Development"; var factory = app.ApplicationServices.GetRequiredService(); factory.AddConsole(); factory.AddDebug(); app.UseDeveloperExceptionPage(); app.UseIISPlatformHandler(options => { options.FlowWindowsAuthentication = false; }); app.UseOverrideHeaders(options => { options.ForwardedOptions = ForwardedHeaders.All; }); app.UseStaticFiles(); // Add a middleware used to validate access // tokens and protect the API endpoints. app.UseOAuthValidation(); // comment this out and you get an error saying // InvalidOperationException: No authentication handler is configured to handle the scheme: Microsoft.AspNet.Identity.External app.UseIdentity(); // TOO: Remove app.UseGoogleAuthentication(options => { options.ClientId = "XXX"; options.ClientSecret = "XXX"; }); app.UseTwitterAuthentication(options => { options.ConsumerKey = "XXX"; options.ConsumerSecret = "XXX"; }); // Note: OpenIddict must be added after // ASP.NET Identity and the external providers. app.UseOpenIddict(options => { options.Options.AllowInsecureHttp = true; options.Options.UseJwtTokens(); }); app.UseMvcWithDefaultRoute(); using (var context = app.ApplicationServices.GetRequiredService()) { context.Database.EnsureCreated(); // Add Mvc.Client to the known applications. if (!context.Applications.Any()) { context.Applications.Add(new Application { Id = "myClient", DisplayName = "My client application", RedirectUri = "http://localhost:5000/signin", LogoutRedirectUri = "http://localhost:5000/", Secret = Crypto.HashPassword("secret_secret_secret"), Type = OpenIddictConstants.ApplicationTypes.Confidential }); context.SaveChanges(); } } } 

现在我的AccountController基本上与普通的帐户控制器相同,虽然一旦用户登录(使用本地和外部登录),我使用此function并需要accessToken。

 private IActionResult RedirectToAngular() { // I need the accessToken here return RedirectToAction(nameof(AccountController.Angular), new { accessToken = token }); } 

正如您在AccountController上的ExternalLoginCallback方法中看到的那样

 public async Task ExternalLoginCallback(string returnUrl = null) { var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { // SHOULDNT THE USER HAVE A LOCAL ACCESS TOKEN NOW?? return RedirectToAngular(); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } 

 var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { // SHOULDNT THE USER HAVE A LOCAL ACCESS TOKEN NOW?? return RedirectToAngular(); } 

这不是它应该如何工作。 以下是经典流程中发生的情况:

  • OAuth2 / OpenID Connect客户端应用程序(在您的情况下,您的Satellizer JS应用程序)将用户代理重定向到授权端点(默认情况下在OpenIddict中为/connect/authorize ),其中包含所有必需参数: client_idredirect_uri (OpenID Connect中必需) , response_typenonce在使用隐式流时(即response_type=id_token token )。 假设您已正确注册授权服务器(1),Satellizer应该为您做到这一点。

  • 如果用户尚未登录,则授权终端会将用户重定向到登录端点(在OpenIddict中,它由内部控制器为您完成)。 此时,将调用AccountController.Login操作,并向用户显示登录表单。

  • 当用户登录时(在注册过程和/或外部认证关联之后),他/她必须被重定向回授权端点: 在此阶段,您无法将用户代理重定向到Angular应用程序 。 撤消对ExternalLoginCallback所做的更改,它应该可以工作。

  • 然后,向用户显示一个同意书,表明他/她将允许您的JS应用程序代表他/她访问他的个人数据。 当用户提交同意表单时,请求由OpenIddict处理,生成访问令牌并将用户代理重定向回JS客户端应用程序,并将令牌附加到URI片段。

[1]:根据Satellizer文档,应该是这样的:

 $authProvider.oauth2({ name: 'openiddict', clientId: 'myClient', redirectUri: window.location.origin + '/done', authorizationEndpoint: window.location.origin + '/connect/authorize', responseType: 'id_token token', scope: ['openid'], requiredUrlParams: ['scope', 'nonce'], nonce: function() { return "TODO: implement appropriate nonce generation and validation"; }, popupOptions: { width: 1028, height: 529 } });