.NET Core Identity Server 4 身份验证 VS 身份验证 [英] .NET Core Identity Server 4 Authentication VS Identity Authentication

查看:44
本文介绍了.NET Core Identity Server 4 身份验证 VS 身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解在 ASP.NET Core 中进行身份验证的正确方法.我查看了几个资源(其中大部分已经过时).

I'm trying to understand the proper way to do authentication in ASP.NET Core. I've looked at several Resource (Most of which are out dated).

使用 ASP.Core 进行身份验证简介

MSDN 身份简介

有些人提供替代解决方案,声明使用基于云的解决方案(例如 Azure AD),或使用 IdentityServer4 并托管我自己的令牌服务器.

Some people provide altenative solutions stating to use a cloud based solution such as Azure AD, or to Use IdentityServer4 and host my own Token Server.

在旧版本的 .Net 中,一种更简单的身份验证形式是创建自定义 Iprinciple 并将其他身份验证用户数据存储在其中.

In Older version Of .Net one of the simpler forms of authentication would be to create an Custom Iprinciple and store additional authentication user data inside.

public interface ICustomPrincipal : System.Security.Principal.IPrincipal
{
    string FirstName { get; set; }

    string LastName { get; set; }
}

public class CustomPrincipal : ICustomPrincipal
{
    public IIdentity Identity { get; private set; }

    public CustomPrincipal(string username)
    {
        this.Identity = new GenericIdentity(username);
    }

    public bool IsInRole(string role)
    {
        return Identity != null && Identity.IsAuthenticated && 
           !string.IsNullOrWhiteSpace(role) && Roles.IsUserInRole(Identity.Name, role);
    }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string FullName { get { return FirstName + " " + LastName; } }
}

public class CustomPrincipalSerializedModel
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }
}

然后您将数据序列化为 cookie 并将其返回给客户端.

Then you would Serialize your data into a cookie and return it back to the client.

public void CreateAuthenticationTicket(string username) {     

    var authUser = Repository.Find(u => u.Username == username);  
    CustomPrincipalSerializedModel serializeModel = new CustomPrincipalSerializedModel();

    serializeModel.FirstName = authUser.FirstName;
    serializeModel.LastName = authUser.LastName;
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    string userData = serializer.Serialize(serializeModel);

    FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
    1,username,DateTime.Now,DateTime.Now.AddHours(8),false,userData);
    string encTicket = FormsAuthentication.Encrypt(authTicket);
    HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
    Response.Cookies.Add(faCookie);
}

我的问题是:

  1. 我如何以类似于以前版本的 .Net 中所做的方式进行身份验证,旧的方式是否仍然有效,或者是否有更新的版本.

  1. How can I authenticate similar to the way done in previous version's of .Net does the old way still work or is there a newer version.

使用自己的令牌服务器与创建自己的自定义原则相比有哪些优缺点?

What are the pros and cons of using your own token server verses creating your own custom principle?

当使用基于云的解决方案或单独的令牌服务器时,您将如何将其与您当前的应用程序集成,我的应用程序中是否仍需要用户表,您将如何将两者关联起来?

When using a cloud based solution or a separate Token server how would you Integrate that with your current application, would I would still need a users table in my application how would you associate the two?

既然有这么多不同的解决方案,我该如何创建企业应用程序,以允许通过 Gmail/Facebook 登录,同时仍然能够扩展到其他 SSO

Being that there are so many different solutions how can I create an enterprise application, to allow Login through Gmail/Facebook while still being able to expand to other SSO's

推荐答案

TL;DR

IdentityServer = 通过 OAuth 2.0/OpenId-Connect 的令牌加密和验证服务

IdentityServer = token encryption and validation services via OAuth 2.0/OpenId-Connect

ASP.NET Identity = ASP.NET 中的当前身份管理策略

ASP.NET Identity = current Identity Management strategy in ASP.NET

我如何以类似于以前版本的 .Net 中所做的方式进行身份验证,旧的方式是否仍然有效,或者是否有更新的版本.

我认为没有理由不能在 ASP.NET Core 中实现旧方法,但总的来说,该策略已被 ASP.NET Identity 所取代,并且 ASP.NET Identity 在 ASP.NET Core 中仍然存在且运行良好.

I see no reason why you couldn't achieve the old way in ASP.NET Core, but in general, that strategy was replaced with ASP.NET Identity, and ASP.NET Identity is alive and well in ASP.NET Core.

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity

ASP.NET Identity 使用像 SQL Server 这样的后备存储来保存用户信息,如用户名、密码(散列)、电子邮件、电话,并且可以轻松扩展以保存名字、姓氏或其他任何内容.因此,真的没有理由将用户信息加密到 cookie 中并将其从客户端来回传递到服务器.它支持用户声明、用户令牌、用户角色和外部登录等概念.以下是 ASP.NET Identity 中的实体:

ASP.NET Identity uses a backing store like SQL Server to hold user information like username, password (hashed), email, phone and easily be extended to hold FirstName, LastName or whatever else. So, there really no reason to encrypt user information into a cookie and pass it back and forth from client to server. It supports notions like user claims, user tokens, user roles, and external logins. Here are the entities in ASP.NET Identity:

  • AspNetUsers
  • AspNetUserRoles
  • AspNetUserClaims
  • AspNetUserLogins(用于链接外部身份提供商,如 Google、AAD)
  • AspNetUserTokens(用于存储用户积累的 access_tokens 和 refresh_tokens 等)

使用自己的令牌服务器与创建自己的自定义原则相比有哪些优缺点?

令牌服务器将是一个生成包含授权和/或身份验证信息的简单数据结构的系统.授权通常采用名为 access_token 的令牌的 for.这将是房子的钥匙",可以这么说,让您通过门口并进入受保护资源的住所,通常是 Web api.对于身份验证,id_token 包含用户/个人的唯一标识符.虽然将这样的标识符放在 access_token 中很常见,但现在有一个专门的协议来做到这一点:OpenID-Connect.

A token server would be a system that generates a simple data structure containing Authorization and/or Authentication information. Authorization usually takes the for of a token named access_token. This would be the "keys to the house", so to speak, letting you through the doorway and into the residence of a protected resource, usually a web api. For Authentication, the id_token contains a unique identifier for a user/person. While it is common to put such an identifier in the access_token, there is now a dedicated protocol for doing that: OpenID-Connect.

拥有自己的安全令牌服务 (STS) 的原因是为了通过加密保护您的信息资产,并控制哪些客户端(应用程序)可以访问这些资源.此外,身份控制标准现在存在于 OpenID-Connect 规范中.IdentityServer 是 OAuth 2.0 授权服务器与 OpenID-Connect 身份验证服务器相结合的示例.

The reason to have your own Security Token Service (STS), would to be to safeguard your information assets, via cryptography, and control which clients (applications) can access those resources. Furthermore, the standards for identity controls now exist in OpenID-Connect specifications. IdentityServer is an example of a OAuth 2.0 Authorization Server combined with an OpenID-Connect Authentication server.

但是,如果您只想在应用程序中使用用户表,那么这些都不是必需的.您不需要令牌服务器 - 只需使用 ASP.NET Identity.ASP.NET 标识将您的用户映射到 ClaimsIdentity 对象 - 无需自定义 IPrincipal 类.

But none of this is necessary if you just want a user table in your application. You don't need a token server- just use ASP.NET Identity. ASP.NET Identity maps your User to a ClaimsIdentity object on the server- no need for a custom IPrincipal class.

当使用基于云的解决方案或单独的令牌服务器时,您将如何将其与您当前的应用程序集成,我的应用程序中是否仍需要用户表,您将如何将两者关联起来?

请参阅这些教程以将单独的身份解决方案与应用程序集成:https://identityserver4.readthedocs.io/en/latest/quickstarts/0_overview.htmlhttps://auth0.com/docs/quickstart/webapp/aspnet-core

See these tutorials for integrating separate identity solutions with an application: https://identityserver4.readthedocs.io/en/latest/quickstarts/0_overview.html https://auth0.com/docs/quickstart/webapp/aspnet-core

您至少需要一个两列表来将用户名映射到外部提供商的用户标识符.这就是 AspNetUserLogins 表在 ASP.NET Identity 中的作用.然而,该表中的行取决于 AspNetUsers 中的用户记录.

At a minimum you would need a two column table mapping the username to the external provider's user identifier. This is what the AspNetUserLogins table does in ASP.NET Identity. The rows in that table however are dependent on the being a User record in AspNetUsers.

ASP.NET Identity 支持 Google、Microsoft、Facebook 等外部提供商,任何 OpenID-Connect 提供商,Azure AD 都已经存在.(谷歌和微软已经实现了 OpenID-Connect 协议,所以你也不需要他们的自定义集成包,比如这个).此外,ADFS 在 ASP.NET Core Identity 上尚不可用.

ASP.NET Identity supports external providers like Google, Microsoft, Facebook, any OpenID-Connect provider, Azure AD are already there. (Google and Microsoft have already implemented the OpenID-Connect protocol so you don't need their custom integration packages either, like this one, for example). Also, ADFS is not yet available on ASP.NET Core Identity.

请参阅此文档以开始使用 ASP.NET Identity 中的外部提供程序:

See this doc to get started with external providers in ASP.NET Identity:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/

既然有这么多不同的解决方案,我该如何创建企业应用程序,以允许通过 Gmail/Facebook 登录,同时仍然能够扩展到其他 SSO

如上所述,ASP.NET Identity 已经做到了这一点.创建外部提供者"表和数据驱动您的外部登录过程相当容易.因此,当出现新的SSO"时,只需添加一个新行,其中包含提供者的 url、客户端 ID 和他们提供给您的机密等属性.ASP.NET Identity 已经在 Visual Studio 模板中内置了 UI,但请参阅 社交登录较冷的按钮.

As explained above, ASP.NET Identity already does this. It's fairly easy to create an "External Providers" table and data drive your external login process. So when a new "SSO" comes along, just add a new row with the properties like the provider's url, the client id and secret they give you. ASP.NET Identity already has the UI built in there Visual Studio templates, but see Social Login for cooler buttons.

总结

如果您只需要具有密码登录功能和用户配置文件的用户表,那么 ASP.NET Identity 是完美的.无需涉及外部机构.但是,如果有许多应用程序需要访问许多 api,那么保护和验证身份和访问令牌的独立权限是有意义的.IdentityServer 非常适合,或查看 openiddict-coreAuth0 用于云解决方案.

If you just need a users table with password sign in capabilities and a user profile, then ASP.NET Identity is perfect. No need to involve external authorities. But, if have many applications needing to access many apis, then an independent authority to secure and validate identity and access tokens makes sense. IdentityServer is a good fit, or see openiddict-core, or Auth0 for a cloud solution.

我很抱歉,这没有达到目标,或者它太介绍性了.请随时互动以找到您正在寻找的靶心.

My apologies is this isn't hitting the mark or if it is too introductory. Please feel free to interact to get to the bulls-eye you are looking for.

附录:Cookie 身份验证

要使用 cookie 进行基本身份验证,请按照以下步骤操作.但是,据我所知,不支持自定义声明主体.要达到相同的效果,请使用 ClaimPrincipal 对象的 Claims 列表.

To do bare bones authentication with cookies, follow these steps. But, to my knowledge a custom claims principal is not supported. To achieve the same effect, utilize the Claims list of the ClaimPrincipal object.

在 Visual Studio 2015/2017 中创建一个新的 ASP.NET Core 1.1 Web 应用程序,在对话框中选择无身份验证".然后添加包:

Create a new ASP.NET Core 1.1 Web Application in Visual Studio 2015/2017 choosing "No Authentication" in the dialog. Then add package:

Microsoft.AspNetCore.Authentication.Cookies

Startup.csConfigure 方法下放置这个(在 app.UseMvc 之前):

Under the Configure method in Startup.cs place this (before app.UseMvc):

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationScheme = "MyCookieMiddlewareInstance",
    LoginPath = new PathString("/Controller/Login/"),
    AutomaticAuthenticate = true,
    AutomaticChallenge = true
});

然后构建一个登录ui并将html表单发布到这样的操作方法中:

Then build a login ui and post the html Form to an Action Method like this:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(String username, String password, String returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        // check user's password hash in database
        // retrieve user info

        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Name, username),
            new Claim("FirstName", "Alice"),
            new Claim("LastName", "Smith")
        };

        var identity = new ClaimsIdentity(claims, "Password");

        var principal = new ClaimsPrincipal(identity);

        await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);

        return RedirectToLocal(returnUrl);
    }

    ModelState.AddModelError(String.Empty, "Invalid login attempt.");

    return View();
}

HttpContext.User 对象应该具有您的自定义声明,并且可以轻松检索 ClaimPrincipal 的 List 集合.

The HttpContext.User object should have your custom claims and are easily retrievable the List collection of the ClaimPrincipal.

我希望这足够了,因为一个完整的解决方案/项目对于 StackOverflow 帖子来说似乎有点多.

I hope this suffices, as a full Solution/Project seems a bit much for a StackOverflow post.

这篇关于.NET Core Identity Server 4 身份验证 VS 身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆