C# 如何为用户获取访问令牌?
我正在使用AngularJs为OpenIddict开发一个示例应用程序。我被告知,您不应该使用像Satellizer这样的客户端框架,因为不建议这样做,而是允许服务器处理服务器端的登录(本地登录和使用外部登录提供程序),并返回访问令牌 我有一个演示angularJs应用程序,使用服务器端登录逻辑并调用angular应用程序,但我的问题是,如何为当前用户获取访问令牌 这是我的startup.cs文件,您可以看到我的配置C# 如何为用户获取访问令牌?,c#,asp.net,.net,openid-connect,openiddict,C#,Asp.net,.net,Openid Connect,Openiddict,我正在使用AngularJs为OpenIddict开发一个示例应用程序。我被告知,您不应该使用像Satellizer这样的客户端框架,因为不建议这样做,而是允许服务器处理服务器端的登录(本地登录和使用外部登录提供程序),并返回访问令牌 我有一个演示angularJs应用程序,使用服务器端登录逻辑并调用angular应用程序,但我的问题是,如何为当前用户获取访问令牌 这是我的startup.cs文件,您可以看到我的配置 public void ConfigureServices(IServiceC
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上的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 });
}
}
public异步任务ExternalLoginCallback(string returnUrl=null)
{
var info=await _signInManager.getexternallogininfosync();
if(info==null)
{
返回重定向到操作(名称(登录));
}
//如果用户已经登录,请使用此外部登录提供程序登录该用户。
var result=wait _signingmanager.externalloginginasync(info.LoginProvider、info.ProviderKey、ispersist:false);
if(result.successed)
{
//用户现在不应该有本地访问令牌吗??
返回重定向到Angular();
}
if(结果要求系数)
{
return RedirectToAction(nameof(SendCode),new{ReturnUrl=ReturnUrl});
}
如果(结果IsLockedOut)
{
返回视图(“锁定”);
}
否则{
//如果用户没有帐户,请要求用户创建帐户。
ViewData[“ReturnUrl”]=ReturnUrl;
ViewData[“LoginProvider”]=info.LoginProvider;
var email=info.ExternalPrincipal.FindFirstValue(ClaimTypes.email);
返回视图(“ExternalLoginConfirmation”,新的ExternalLoginConfirmationViewModel{Email=Email});
}
}
这不是它的工作原理。以下是经典流程中发生的情况:
- OAuth2/OpenID Connect客户端应用程序(在您的情况下,您的Satellizer JS应用程序)使用所有必需参数将用户代理重定向到授权端点(
,在OpenIddict中默认为/Connect/authorize
,客户端id
),重定向uri
和response\u type
使用隐式流时(即nonce
)。假设您已经正确注册了授权服务器(1),卫星导航器应该为您这样做response\u type=id\u令牌
- 如果用户尚未登录,授权端点将用户重定向到登录端点(在OpenIddict中,由内部控制器为您完成)。此时,将调用您的
操作,并向用户显示一个登录表单AccountController.Login
- 当用户登录时(在注册过程和/或外部身份验证关联之后),他/她必须重定向回授权端点:在此阶段无法将用户代理重定向到Angular应用程序。撤消对
所做的更改,它应该可以工作ExternalLoginCallback
- 然后,用户将显示一份同意书,表示他/她将允许您的JS应用程序代表他/她访问他的个人数据。当用户提交同意书时,请求由OpenIddict处理,生成一个访问令牌,并将用户代理重定向回JS客户端应用程序,令牌附加到URI片段
$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 }
});
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();
}
$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 }
});