your programing

ASP.NET Core 2.0 인증 미들웨어

lovepro 2020. 10. 9. 11:32
반응형

ASP.NET Core 2.0 인증 미들웨어


Core 1.1에서는 @blowdart의 조언에 따라 맞춤형 미들웨어를 구현했습니다.

https://stackoverflow.com/a/31465227/29821

다음과 같이 작동했습니다.

  1. 미들웨어가 실행되었습니다. 요청 헤더에서 토큰을 가져 왔습니다.
  2. 토큰을 확인하고 유효한 경우 여러 클레임을 포함하는 ID (ClaimsIdentity)를 구축 한 다음 HttpContext.User.AddIdentity ()를 통해 추가했습니다.
  3. services.AddAuthorization을 사용하는 ConfigureServices에서 미들웨어에서 제공하는 클레임을 요구하는 정책을 추가했습니다.
  4. 컨트롤러 / 액션에서 [Authorize (Roles = "미들웨어가 추가 한 일부 역할")]을 사용합니다.

토큰이 유효하지 않고 (위의 2 단계) 클레임이 추가되지 않은 경우 "No authenticationScheme이 지정되었으며 DefaultChallengeScheme을 찾을 수 없음"이 표시된다는 점을 제외하면 2.0에서 다소 작동합니다.

이제 2.0에서 변경된 인증을 읽고 있습니다.

https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x

ASP.NET Core 2.0에서 동일한 작업을 수행하는 올바른 경로는 무엇입니까? 진정한 사용자 지정 인증을 수행하는 예가 보이지 않습니다.


따라서이 문제를 해결하기 위해 하루 종일 노력한 끝에 마침내 Microsoft가 코어 2.0에서 새로운 단일 미들웨어 설정을위한 사용자 지정 인증 처리기를 만드는 방법을 알아 냈습니다.

MSDN에 대한 몇 가지 설명서를 살펴본 후 인터페이스 AuthenticationHandler<TOption>를 구현 하는 클래스를 찾았습니다 IAuthenticationHandler.

거기에서 https://github.com/aspnet/Security 에있는 기존 인증 체계가있는 전체 코드베이스를 찾았습니다.

이들 중 하나에서 Microsoft가 JwtBearer 인증 체계를 구현하는 방법을 보여줍니다. ( https://github.com/aspnet/Security/tree/master/src/Microsoft.AspNetCore.Authentication.JwtBearer )

해당 코드의 대부분을 새 폴더에 복사하고 .NET과 관련된 모든 작업을 지 웠습니다 JwtBearer.

에서 JwtBearerHandler클래스 (연장 AuthenticationHandler<>)에 대한 재정의있다Task<AuthenticateResult> HandleAuthenticateAsync()

난 그냥 뱉어, 사용자 정의 토큰 서버를 통해 주장을 설정하기위한 우리의 오래된 미들웨어에 추가, 여전히 권한을 가진 몇 가지 문제가 발생했다 200 OK대신을 401 Unauthorized토큰이 유효하고 어떤 주장이 설정되지 때.

나는 Task HandleChallengeAsync(AuthenticationProperties properties)어떤 이유로 든 [Authorize(Roles="")]컨트롤러에서 권한을 설정하는 데 사용되는 재정의했다는 것을 깨달았습니다 .

이 재정의를 제거한 후 코드가 작동 401하고 권한이 일치하지 않을 때 성공적으로 a를 던 졌습니다.

이에서 주요 테이크 아웃 이제 사용자 지정 미들웨어를 사용할 수 있다는 것입니다, 당신은을 통해 구현해야 AuthenticationHandler<>당신은 설정해야 DefaultAuthenticateScheme하고 DefaultChallengeScheme사용하는 경우 services.AddAuthentication(...).

다음은이 모든 것이 어떻게 생겼는지에 대한 예입니다.

Startup.cs / ConfigureServices ()에서 다음을 추가하십시오.

services.AddAuthentication(options =>
{
    // the scheme name has to match the value we're going to use in AuthenticationBuilder.AddScheme(...)
    options.DefaultAuthenticateScheme = "Custom Scheme";
    options.DefaultChallengeScheme = "Custom Scheme";
})
.AddCustomAuth(o => { });

Startup.cs / Configure ()에서 다음을 추가하십시오.

app.UseAuthentication();

새 파일 CustomAuthExtensions.cs 만들기

public static class CustomAuthExtensions
{
    public static AuthenticationBuilder AddCustomAuth(this AuthenticationBuilder builder, Action<CustomAuthOptions> configureOptions)
    {
        return builder.AddScheme<CustomAuthOptions, CustomAuthHandler>("Custom Scheme", "Custom Auth", configureOptions);
    }
}

새 파일 CustomAuthOptions.cs 만들기

public class CustomAuthOptions: AuthenticationSchemeOptions
{
    public CustomAuthOptions()
    {

    }
}

새 파일 CustomAuthHandler.cs 만들기

internal class CustomAuthHandler : AuthenticationHandler<CustomAuthOptions>
{
    public CustomAuthHandler(IOptionsMonitor<CustomAuthOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock)
    {
        // store custom services here...
    }
    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        // build the claims and put them in "Context"; you need to import the Microsoft.AspNetCore.Authentication package
        return AuthenticateResult.NoResult();
    }
}

There are considerable changes in Identity from Core 1.x to Core 2.0 as the article you reference points out. The major change is getting away from the middleware approach and using dependency injection to configure custom services. This provides a lot more flexibility in customizing Identity for more complex implementations. So you want to get away from the middleware approach you mention above and move towards services. Follow the migration steps in the referenced article to achieve this goal. Start by replacing app.UseIdentity with app.UseAuthentication. UseIdentity is depreciated and will not be supported in future versions. For a complete example of how to insert a custom claims transformation and perform authorization on the claim view this blog post.

참고URL : https://stackoverflow.com/questions/45805411/asp-net-core-2-0-authentication-middleware

반응형