1

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

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

这是我的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 与普通的 AccountController 基本相同,尽管一旦用户登录(使用本地和外部登录)我使用此功能并需要一个 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 });
    }
}
4

1 回答 1

3
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 应用程序)使用所有必需参数将用户代理重定向到授权端点(/connect/authorize默认情况下在 OpenIddict 中):client_id, redirect_uri(在 OpenID Connect 中是必需的),response_type并且nonce在使用隐式流(即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 }
});
于 2016-01-15T23:40:15.530 回答