我正在使用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<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与普通帐户控制器基本相同,但是一旦用户登录(使用本地和外部登录),我就会使用此功能并需要一个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 });
}
}
答案 0 :(得分: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应用程序)使用所有必需参数将用户代理重定向到授权端点(默认情况下在OpenIddict中为/connect/authorize
):{{ 1}},client_id
(在OpenID Connect中是必需的),redirect_uri
和response_type
在使用隐式流时(即nonce
)。假设您已正确注册授权服务器(1),Satellizer应该为您做到这一点。
如果用户尚未登录,则授权终端会将用户重定向到登录终端(在OpenIddict中,内部控制器已为您完成)。此时,您的response_type=id_token token
操作将被调用,并且用户将显示一个登录表单。
当用户登录时(在注册过程和/或外部认证关联之后),他/她必须被重定向回授权端点:您无法重定向用户在此阶段代理您的Angular应用。撤消对AccountController.Login
所做的更改,它应该有效。
然后,用户会显示一份同意书,表明他/她将允许您的JS应用程序代表他/她访问其个人数据。当用户提交同意书时,请求由OpenIddict处理,生成访问令牌并将用户代理重定向回JS客户端应用程序,并将令牌附加到URI片段。
[1]:根据Satellizer文档,它应该是这样的:
ExternalLoginCallback