External Identity Provider with ASP.NET Core Identity - Code Maze (code-maze.com)

应该是要参考这个

active-directory-aspnetcore-webapp-openidconnect-v2/1-WebApp-OIDC/1-1-MyOrg at master · Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2 · GitHub

微软官方的介绍

Introduction to Identity on ASP.NET Core | Microsoft Learn

 

Community OSS authentication options for ASP.NET Core | Microsoft Learn

OSS authentication providers [.NET]

Name Description
IdentityServer IdentityServer is an OpenID Connect and OAuth 2.0 framework for ASP.NET Core.
OpenIddict Flexible and versatile OAuth 2.0/OpenID Connect stack for .NET.
AspNet.Security.OAuth.Providers A collection of security middleware for ASP.NET Core apps to support social authentication
AspNet.Security.OpenId.Providers A collection of security middleware for ASP.NET Core apps to support OpenID 2.0 authentication providers like Steam
Authentik Authentik is an open-source Identity Provider focused on flexibility and versatility

 

ASP.NET Core Identity Series - Code Maze (code-maze.com)

This Tutorial Will be Separated Into Several Parts:

Well, a lot of ground to cover.

External Identity Provider with ASP.NET Core Identity - Code Maze (code-maze.com)

Using an external identity provider while login to the application is a quite common case. This enables us to log in with our external accounts like Google, Facebook, etc. By using ASP.NET Core Identity, we are going to see that this is not a hard process at all.

So, in this article, we are going to learn how to configure an external identity provider in our ASP.NET Core application and how to use a Google account to log in to our application. Of course, in a very similar way, you can configure any other external account.

One important thing to know here. Once an external user logs in to our system, they will always bring an identifier that is unique for that user in our system. That user could have different Ids for different sites but for our site, that Id will always be the same.

To download the source code for this project, you can visit the External Identity Provider with ASP.NET Core Identity repository.

To navigate through the entire series, visit the ASP.NET Core Identity series page.

So, let’s get on it.

 

Google API Platform

申请Client id和Client Secret

 

External Identity Provider configuration

配置

Now, we are going to register Google as our external identity provider. To do that, we have to install the Microsoft.AspNetCore.Authentication.Google package first:

 

After the installation, we have to modify the appsettings.json file:

 

Now let’s configure Google as an external provider by modifying the ConfigureServices method in .NET 5 or previous versions:

 

The AddIdentity method configures default scheme settings. But the AddAuthentication allows configuring different authentication options, like Google for example. That’s why this method must be placed below the AddIdentity method.

 

Now, let’s create the _ExternalAuthentication partial view, to support external authentication

@using Microsoft.AspNetCore.Identity
@using IdentityByExamples.Models

@inject SignInManager<User> SignInManager

<div class="col-md-4 offset-2">
    <section>
        <h4>Use different service for log in:</h4>
        <hr />
        @{
            var providers = (await SignInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (!providers.Any())
            {
                <div>
                    <p>
                        We couldn't find any external provider
                    </p>
                </div>
            }
            else
            {
                <form asp-action="ExternalLogin" asp-route-returnurl="@ViewData["ReturnUrl"]" method="post" class="form-horizontal">
                    <div>
                        <p>
                            @foreach (var provider in providers)
                            {
                                <input type="submit" class="btn btn-info" value="@provider.Name" name="provider" />
                            }
                        </p>
                    </div>
                </form>
            }
        }
    </section>
</div>

By using the SignInManager.GetExternalAuthenticationSchemesAsync method, we fetch all the registered providers in our application. And if we find any, we show it in the view. So, in order to see these changes, let’s just include this partial view in the Login view:

<div class="col-md-4">
    <form asp-action="Login" asp-route-returnUrl="@ViewData["ReturnUrl"]">
          //code removed for clarity reasons  
    </form>
</div>
<partial name="_ExternalAuthentication" />

Now, if we navigate to the Login view:

This looks great. Now, we can implement actions in the Account controller.

 

External Identity Provider Implementation

The form the _ExternalAuthentication partial view alreadt targets the ExternalLogin action. So we have to create it and add the required logic:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult ExternalLogin(string provider, string returnUrl = null)
{
    var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
    var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
    return Challenge(properties, provider);
}

This is the action that we target by clicking the google button. It has two parameters: provider and returnUrl. If you take a look at the submit button code, you are going to see the name attribute with the provider value. Therefore, MVC will pair the value from that button to the provider parameter in this action. The second parameter is populated through the URI.

 

Inside the action, we create two variables: redirectUrl and properties. We assign the redirect address to the first variable and use the ConfigureExternalAuthenticationProperties method to create an object of type AuthenticationProperties that contains our provider and redirectUrl:

 

After that, we return a challenge. With it, we challenge a user to provide an identity supplied by the provider, in this case, Google.

Of course, we have to implement the ExternalLoginCallback action.

Additional Implementation

So, let’s create a new action and add the required logic:

[HttpGet]
public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null)
{
    var info = await _signInManager.GetExternalLoginInfoAsync();
    if (info == null)
    {
        return RedirectToAction(nameof(Login));
    }

    var signInResult = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypassTwoFactor: true);
    if(signInResult.Succeeded)
    {
        return RedirectToLocal(returnUrl);
    }
    if(signInResult.IsLockedOut)
    {
        return RedirectToAction(nameof(ForgotPassword));
    }
    else
    {
        ViewData["ReturnUrl"] = returnUrl;
        ViewData["Provider"] = info.LoginProvider;
        var email = info.Principal.FindFirstValue(ClaimTypes.Email);
        return View("ExternalLogin", new ExternalLoginModel { Email = email });
    }
}

With the GetExternalLoginInfoAsync method, we collect exactly that – external login info. So the information like provider, given name, last name, email, name identifier, etc, are going to be provided in the info variable. If it’s not null we try to sign in a user with an external provider by using the ExternalLoginSignInAsync method. If this succeeds, we redirect the user to the Home or some other view.

On the other hand, if the account is locked out, we currently just redirect to the ForgotPassword view, but you can implement a different logic that suits your needs. Finally, if nothing checks out, we extract an email and the provider from the info variable and redirect the user to the ExternalLogin view, where they need to associate an external account to the existing one.

If you want users to manually enter their email address, you have to remove the Email property initialization in the ExternalLoginModel.

As you can see, we are missing some parts of this action. So, let’s add those.

 

ExternalLogin and ExternalLoginConfirmation Implementation

The first thing, we are going to do is to add the ExternalLoginModel class:

 

So, we first check for the model validity and check the external login info as in the previous action. Then, we try to get a user from the database. If exists, we just associate this external account with the existing one by adding another entry in the AspNetUserLogins table and sign in the user. But if we can’t find a user, we create a new one in the AspNetUsers table, connect the external account with the AddLoginAsync method and sing in that user. Of course, we didn’t want to repeat the same code, but you can extract the code for sending a confirmation email and adding a role to the user in the separate method and call it in here.

Finally, if something fails, we collect errors and return a view.

 

Conclusion

So, that’s all it takes to configure and integrate an external identity provider into our ASP.NET Core application.

To sum up. We have learned:

  • How to configure our project with the Google API
  • The way to configure External Identity Provider in our application
  • How to implement External Identity Provider with actions and views

We hope you have enjoyed this article and the complete series as well.

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(41)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-07-12 Difference between Github Copilot and Github Copilot Nightly.
2022-07-12 Learn Vue 3, a Front-End JavaScript Framework
2022-07-12 Difference between Return and Break statements
2022-07-12 What does threadsafe mean?
2022-07-12 Use anonymous type for LINQ based lists instead of var
2021-07-12 JavaScript--> JavaScript reference--> Statements and declarations--> import
2021-07-12 npm outdated -g --depth=0
点击右上角即可分享
微信分享提示