Sam*_*Sam 16 javascript c# asp.net-identity identityserver4 angular
使用带有ASP.NET身份的Identity Server 4添加身份验证功能后,我计划添加Google提供商,以便用户也可以使用他们的Google +帐户登录.我使用Angular作为我的前端,使用ASP.NET Web Api(Core)作为后端.
// Login client
public login(email: string, password: string): Observable<any> {
let body: any = this.encodeParams({ /* cliend_id, grant_type, username, password, scope */ });
return this.http.post("http://localhost:64023/connect/token", body, this.options)
.map((res: Response) => {
const body: any = res.json();
if (typeof body.access_token !== "undefined") {
// Set localStorage with id_token,..
}
}).catch((error: any) => { /**/ );
}
// Register Web API
[HttpPost("Create")]
[AllowAnonymous]
public async Task<IActionResult> Create([FromBody]CreateUserViewModel model)
{
var user = new ApplicationUser
{
FirstName = model.FirstName,
LastName = model.LastName,
AccessFailedCount = 0,
Email = model.Email,
EmailConfirmed = false,
LockoutEnabled = true,
NormalizedEmail = model.Email.ToUpper(),
NormalizedUserName = model.Email.ToUpper(),
TwoFactorEnabled = false,
UserName = model.Email
};
var result = await _userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await addToRole(model.Email, "user");
await addClaims(model.Email);
}
return new JsonResult(result);
}
// Identity Server Startup
app.UseGoogleAuthentication(new GoogleOptions
{
AuthenticationScheme = "Google",
DisplayName = "Google",
SignInScheme = "Identity.External",
// ClientId, ClientSecret,..
});
Run Code Online (Sandbox Code Playgroud)
用户登录后,localStorage已设置,我可以保护安全的控制器.对于Google提供商,我添加了一个额外的按钮和以下方法:
initGoogleAPI() {
let self = this;
gapi.load('auth2', function () {
self.auth2 = gapi.auth2.init({ /* client_id, cookiepolicy, scope */ });
self.externalLogin(document.getElementById('google-button'));
});
}
externalLogin(element) {
let self = this;
this.auth2.attachClickHandler(element, {},
function (googleUser) {
// retrieved the id_token, name, email,...
}, function (error) {
alert(JSON.stringify(error, undefined, 2));
});
}
Run Code Online (Sandbox Code Playgroud)
我找到了一些解决方案,但仅适用于MVC应用程序,而不适用于使用客户端框架的SPA.我需要采取哪些步骤才能使外部登录工作?当用户首次使用外部提供商登录时,是否需要在AspNetUsers表中创建新记录?
登录应由 IdentityServer4 处理。无论是本地登录还是第三方登录,它都应该向 Web 应用程序返回类似的令牌。
如果您的 Web API 后端需要用户数据,则应将其作为声明传递。
IdentityServer4 快速入门可能对您的代码有帮助,他们有一个关于外部登录的示例,您可以将其添加到 IdentityServer 以及如何从JavaScript 应用程序执行登录流程。
| 归档时间: |
|
| 查看次数: |
1975 次 |
| 最近记录: |