Programing

.NET Core Identity Server 4 인증 VS ID 인증

lottogame 2020. 11. 21. 08:18
반응형

.NET Core Identity Server 4 인증 VS ID 인증


ASP.NET Core에서 인증을 수행하는 적절한 방법을 이해하려고합니다. 여러 리소스를 살펴 봤습니다 (대부분 구식 임).

일부 사람들은 Azure AD와 같은 클라우드 기반 솔루션을 사용하거나 IdentityServer4를 사용하고 자체 토큰 서버를 호스팅하는 대체 솔루션을 제공합니다.

이전 버전의 .Net에서 더 간단한 인증 형식 중 하나는 사용자 지정 Iprinciple을 만들고 추가 인증 사용자 데이터를 내부에 저장하는 것입니다.

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

그런 다음 데이터를 쿠키로 직렬화하고 클라이언트에 다시 반환합니다.

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에서 수행 한 방식과 유사한 인증 방법은 이전 방식이 여전히 작동하거나 최신 버전이 있습니까?

  2. 고유 한 사용자 지정 원칙을 만드는 고유 한 토큰 서버 구절을 사용할 때의 장단점은 무엇입니까?

  3. 클라우드 기반 솔루션 또는 별도의 토큰 서버를 사용할 때이를 현재 애플리케이션과 어떻게 통합 하시겠습니까? 여전히 내 애플리케이션에 사용자 테이블이 필요합니까? 두 가지를 어떻게 연결 하시겠습니까?

  4. 다른 SSO로 확장 할 수있는 동시에 Gmail / Facebook을 통한 로그인을 허용하기 위해 엔터프라이즈 애플리케이션을 만드는 방법에는 여러 가지 솔루션이 있습니다.

  5. 이러한 기술의 간단한 구현은 무엇입니까?

TL; DR

IdentityServer = OAuth 2.0 / OpenId-Connect를 통한 토큰 암호화 및 유효성 검사 서비스

ASP.NET ID = ASP.NET의 현재 ID 관리 전략

이전 버전의 .Net에서 수행 한 방식과 유사한 인증 방법은 이전 방식이 여전히 작동하거나 최신 버전이 있습니까?

ASP.NET Core에서 이전 방식을 달성 할 수없는 이유는 알 수 없지만 일반적으로 해당 전략은 ASP.NET ID로 대체되었으며 ASP.NET ID는 ASP.NET Core에서 잘 작동합니다.

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

ASP.NET Identity는 SQL Server와 같은 백업 저장소를 사용하여 사용자 이름, 암호 (해시 됨), 전자 메일, 전화와 같은 사용자 정보를 보유하고 FirstName, LastName 또는 기타 모든 것을 보유하도록 쉽게 확장 할 수 있습니다. 따라서 사용자 정보를 쿠키로 암호화하고 클라이언트에서 서버로 앞뒤로 전달할 이유가 없습니다. 사용자 클레임, 사용자 토큰, 사용자 역할 및 외부 로그인과 같은 개념을 지원합니다. 다음은 ASP.NET ID의 엔터티입니다.

  • AspNetUsers
  • AspNetUserRoles
  • AspNetUserClaims
  • AspNetUserLogins (Google, AAD와 같은 외부 ID 공급자 연결 용)
  • AspNetUserTokens (사용자가 수집 한 access_tokens 및 refresh_tokens와 같은 항목 저장 용)

고유 한 사용자 지정 원칙을 만드는 고유 한 토큰 서버 구절을 사용할 때의 장단점은 무엇입니까?

토큰 서버는 인증 및 / 또는 인증 정보를 포함하는 간단한 데이터 구조를 생성하는 시스템입니다. 인증은 일반적으로 access_token 이라는 토큰을 받습니다. 말하자면 이것은 "집으로가는 열쇠"라고 말하면 출입구를 통해 보호 된 리소스 (일반적으로 웹 API)의 거주지로 들어갈 수있게합니다. 인증의 경우 id_token에 사용자 / 개인에 대한 고유 식별자 포함됩니다. 그러한 식별자를 access_token에 넣는 것이 일반적이지만,이를위한 전용 프로토콜이 있습니다 : OpenID-Connect .

자체 보안 토큰 서비스 (STS)를 갖는 이유는 암호화를 통해 정보 자산을 보호하고 이러한 리소스에 액세스 할 수있는 클라이언트 (애플리케이션)를 제어하기위한 것입니다. 또한 ID 제어에 대한 표준은 이제 OpenID-Connect 사양에 존재합니다. IdentityServer는 OpenID-Connect 인증 서버와 결합 된 OAuth 2.0 인증 서버의 예입니다.

그러나 응용 프로그램에 사용자 테이블 만 있으면이 중 어느 것도 필요하지 않습니다. 토큰 서버가 필요하지 않습니다. ASP.NET ID 만 사용하면됩니다. ASP.NET Identity는 사용자를 서버 ClaimsIdentity 개체에 매핑 하므로 사용자 지정 IPrincipal 클래스가 필요하지 않습니다.

클라우드 기반 솔루션 또는 별도의 토큰 서버를 사용할 때이를 현재 애플리케이션과 어떻게 통합 하시겠습니까? 여전히 내 애플리케이션에 사용자 테이블이 필요합니까? 두 가지를 어떻게 연결 하시겠습니까?

별도의 ID 솔루션을 애플리케이션과 통합하려면 다음 자습서를 참조하십시오. https://identityserver4.readthedocs.io/en/latest/quickstarts/0_overview.html https://auth0.com/docs/quickstart/webapp/aspnet-core

최소한 사용자 이름을 외부 공급자의 사용자 식별자에 매핑하는 두 개의 열 테이블이 필요합니다. 이것이 ASP.NET Identity에서 AspNetUserLogins 테이블이 수행하는 작업입니다. 그러나 해당 테이블의 행은 AspNetUsers의 사용자 레코드에 따라 다릅니다.

ASP.NET ID는 Google, Microsoft, Facebook, 모든 OpenID-Connect 공급자, Azure AD와 같은 외부 공급자를 지원합니다. (Google과 Microsoft는 이미 OpenID-Connect 프로토콜을 구현 했으므로 예를 들어 이와 같은 맞춤형 통합 패키지가 필요하지 않습니다 .) 또한 ADFS는 ASP.NET Core ID에서 아직 사용할 수 없습니다.

ASP.NET Identity에서 외부 공급자를 시작하려면이 문서를 참조하십시오.

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

다른 SSO로 확장 할 수있는 동시에 Gmail / Facebook을 통한 로그인을 허용하기 위해 엔터프라이즈 애플리케이션을 만드는 방법에는 여러 가지 솔루션이 있습니다.

위에서 설명한 것처럼 ASP.NET Identity는 이미이 작업을 수행합니다. "외부 공급자"테이블을 만들고 데이터가 외부 로그인 프로세스를 구동하는 것은 매우 쉽습니다. 따라서 새 "SSO"가 나오면 제공 업체의 URL, 클라이언트 ID 및 비밀번호와 같은 속성이있는 새 행을 추가하면됩니다. ASP.NET ID에는 이미 Visual Studio 템플릿에 UI가 내장되어 있지만 더 멋진 단추는 소셜 로그인참조하십시오 .

요약

암호 로그인 기능과 사용자 프로필이있는 사용자 테이블 만 필요한 경우 ASP.NET ID가 완벽합니다. 외부 기관을 개입시킬 필요가 없습니다. 그러나 많은 API에 액세스해야하는 많은 애플리케이션이있는 경우 ID 및 액세스 토큰을 보호하고 유효성을 검사하는 독립적 인 권한이 필요합니다. IdentityServer가 적합하거나 클라우드 솔루션의 경우 openiddict-core 또는 Auth0참조하십시오 .

제 사과는 이것이 성공하지 못하거나 너무 입문이라는 것입니다. 찾고있는 과녁에 도달하기 위해 자유롭게 상호 작용하십시오.

부록 : 쿠키 인증

쿠키로 베어 본 인증을 수행하려면 다음 단계를 따르십시오. 그러나 내가 아는 한 사용자 지정 클레임 주체는 지원되지 않습니다. 동일한 효과를 얻으려면 ClaimPrincipal개체 의 클레임 목록을 활용하십시오 .

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

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

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

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

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


TL;DR

I would really like to Show A Full posting on how to properly implement IdentityServer4 but I tried to fit All of the Text in but it was beyond the limit of what StackOverflow Accepts so instead I will right some tips and things I've learned.

What are the Benefits of using a Token Server Vs ASP Identity?

A token server, has a lot of benefit's but it isn't right for everyone. If you are implementing an enterprise like solution, where you want multiple client to be able to login, Token server is your best bet, but if you just making a simple website that want to support External Logins, You can get Away With ASP Identity and some Middleware.

Identity Server 4 Tips

Identity server 4 is pretty well documented compared to a lot of other frameworks I've seen but it's hard to start from scratch and see the whole picture.

My first mistak was trying to use OAuth as authentication, Yes, there are ways to do so but OAuth is for Authorization not authentication, if you want to Authenticate use OpenIdConnect (OIDC)

In my case I wanted to create A javascript client, who connects to a web api. I looked at a lot of the solutions, but initially I tried to use the the webapi to call the Authenticate against Identity Server and was just going to have that token persist because it was verified against the server. That flow potentially can work but It has a lot of flaws.

Finally the proper flow when I found the Javascript Client sample I got the right flow. You Client logs in, and sets a token. Then you have your web api consume the OIdc Client, which will verify you're access token against IdentityServer.

Connecting to Stores and Migrations I had a lot of a few misconceptions with migrations at first. I was under the impression that running a migration Generated the SQL from the dll internally, instead of using you're configured Context to figure out how to create the SQL.

There are two syntaxes for Migrations knowing which one your computer uses is important:

dotnet ef migrations add InitialIdentityServerMigration -c ApplicationDbContext

Add-Migration InitialIdentityServerDbMigration -c ApplicationDbContext

I think the parameter after the Migration is the name, why you need a name I'm not sure, the ApplicationDbContext is a Code-First DbContext in which you want to create.

Migrations use some auto-magic to find you're Connection string from how your start up is configured, I just assumed it used a connection from the Server Explorer.

If you have multiple projects make sure you have the project with the ApplicationDbContext set as your start up.

There is a lot of moving parts when Implementing Authorization and Authentication, Hopefully, this post helps someone. The easiest way to full understand authentications is to pick apart their examples to piece everything together and make sure your read the documentation


I have always used the built in ASP.NET Identity (and previously Membership) authorisation/authentication, I have implemented Auth0 recently (https://auth0.com) and recommend this as something else to try.


Social logins are not hard to implement with Identity, but there is some initial setup involved and sometimes the steps you find online in the docs are not identical, usually you can find help for that under the developers section of the platform you are trying to setup the social logins for. Identity is the replacement of the old membership functionality found in legacy versions of the .net framework.What I have found surprising is that edge use cases, like passing a jwt token you already have to a web api are not covered anywhere in the examples online even on pluralsight, I am sure you don't need your own token authority to do this but I have not found a single example on how to pass data in a get or post that isn't dealing with a self-hosted server.


ASP.NET Identity - this is the build in a way to authenticate your application whether it is Bearer or Basic Authentication, It gives us the readymade code to perform User registration, login, change the password and all.

Now consider we have 10 different applications and it is not feasible to do the same thing in all 10 apps. that very fragile and very bad practice.

to resolve this issue what we can able to do is centralize our Authentication and authorization so whenever any change with this will not affect all our 10 apps.

The identity server provides you the capability to do the same. we can create one sample web app which just used as Identity service and it will validate your user and provide s some JWT access token.

참고URL : https://stackoverflow.com/questions/42121854/net-core-identity-server-4-authentication-vs-identity-authentication

반응형