gpt4 book ai didi

c# - OpenIddict - 如何获取用户的访问 token ?

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:48 26 4
gpt4 key购买 nike

我正在使用 AngularJs 为 OpenIddict 开发一个示例应用程序。有人告诉我,您不应该使用像 Satellizer 这样的客户端框架,因为不推荐这样做,而是允许服务器处理服务器端的登录(本地和使用外部登录提供程序),并返回访问 token 。

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

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

public void ConfigureServices(IServiceCollection services) {
var configuration = new ConfigurationBuilder()
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();

services.AddMvc();

services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration["Data:DefaultConnection:ConnectionString"]));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddOpenIddict();

services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
env.EnvironmentName = "Development";

var factory = app.ApplicationServices.GetRequiredService<ILoggerFactory>();
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<ApplicationDbContext>()) {
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 与普通的 Account Controller 基本相同,尽管一旦用户登录(使用本地和外部登录)我就使用此功能并需要 accessToken。

private IActionResult RedirectToAngular()
{
// I need the accessToken here

return RedirectToAction(nameof(AccountController.Angular), new { accessToken = token });
}

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

public async Task<IActionResult> 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 中,这是由内部 Controller 为您完成的)。此时,将调用您的 AccountController.Login 操作并向用户显示一个登录表单。

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

  • 然后,用户会看到一份同意书,表明他/她将允许您的 JS 应用代表他/她访问他/她的个人数据。当用户提交同意书时,请求由 OpenIddict 处理,生成访问 token ,用户代理被重定向回 JS 客户端应用程序, token 附加到 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 }
});

关于c# - OpenIddict - 如何获取用户的访问 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34809639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com