javascript - 使用 Identity Server 4 和 ASP.NET Identity 添加外部登录

标签 javascript c# angular asp.net-identity identityserver4

在使用带有 ASP.NET Identity 的 Identity Server 4 添加身份验证功能后,我计划添加 Google Provider,以便用户也可以使用他们的 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,..
});

用户登录后,localStorage 得到设置,我能够保护安全 Controller 。对于 Google Provider,我添加了一个额外的按钮和以下方法:

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));
    });
}

我找到了一些解决方案,但仅适用于 MVC 应用程序,不适用于使用客户端框架的 SPA。接下来我需要执行哪些步骤才能使外部登录生效?用户第一次使用外部提供商登录时,是否需要在 AspNetUsers 表中创建一条新记录?

最佳答案

您可以检查这个存储库,您可以忽略 ids4 服务器项目并检查 Angular 客户端您应该使用 openid 客户端来执行此操作,然后客户端将被重定向到您登录的 ids4 项目登录页面并返回一个 token 你保存它以便以后使用它

https://github.com/nertilpoci/Aspnetcore-identityserver4-webapi-angular

https://github.com/nertilpoci/Aspnetcore-identityserver4-webapi-angular/tree/master/ClientApp

关于javascript - 使用 Identity Server 4 和 ASP.NET Identity 添加外部登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45709914/

相关文章:

javascript - 滚动到页面的特定部分后启动 CSS 动画

javascript - 如何获得发生碰撞的直线的百分比?

c# - 使用 RegEx c# 从文本中提取电子邮件地址

c# - String.Format 带分机号的电话号码

setTimeout 的 Angular2 异步测试问题

css - ionic2 - 更改 .loadcontent 的字体属性

javascript - 链接元素上的 click() 返回 TypeError ... 为什么?

javascript - 如何选择 HTML 标签之间的某些文本而不是 anchor 标签

c# - VS Code Intellisense 未在 C# 中显示建议

java - Selenium Java 无法选择 AngularJS 元素