programing

웹 API 인증 필터의 경우 내 클레임 ID가 항상 거짓인 이유는 무엇입니까?

randomtip 2023. 6. 10. 16:35
반응형

웹 API 인증 필터의 경우 내 클레임 ID가 항상 거짓인 이유는 무엇입니까?

웹 API 프로젝트에서 저는 토큰을 확인하기 위해 일반 인증 프로세스를 대신합니다.코드는 다음과 같습니다.

if ( true ) // validate the token or whatever here
{
    var claims = new List<Claim>();
    claims.Add( new Claim( ClaimTypes.Name, "MyUser" ) );
    claims.Add( new Claim( ClaimTypes.NameIdentifier, "MyUserID" ) );
    claims.Add( new Claim( ClaimTypes.Role, "MyRole" ) );

    var claimsIdentity = new ClaimsIdentity( claims );

    var principal = new ClaimsPrincipal( new[] { claimsIdentity } );
    Thread.CurrentPrincipal = principal;
    HttpContext.Current.User = principal;
}

그리고 나서 나중에 제가 그것을 바를 때.[Authorize]컨트롤러에 대한 속성으로, 인증에 실패합니다.

디버그 코드는 동일한 동작을 확인합니다.

// ALWAYS FALSE!
if ( HttpContext.Current.User.Identity.IsAuthenticated ) {
    // do something
}

유효한 클레임 ID를 구성하여 스레드에 할당했는데도 사용자가 인증되지 않았다고 생각하는 이유는 무엇입니까?

문제는 의 깨진 변화 때문입니다.넷 4.5. 기사에서 설명한 바와 같이, 단순히 클레임 ID를 구성하는 것만으로는 IsAuthenticated return이 더 이상 성립되지 않습니다.대신 어떤 문자열(무엇이든 상관 없음)을 생성자에게 전달해야 합니다.

그래서 위 코드의 이 행은 다음과 같습니다.

var claimsIdentity = new ClaimsIdentity( claims );

다음 항목이 됩니다.

// exact string doesn't matter
var claimsIdentity = new ClaimsIdentity( claims, "CustomApiKeyAuth" );

그리고 문제는 해결되었습니다.업데이트: Leo의 다른 답변을 참조하십시오.정확한 인증인증 파이프라인에 있는 다른 항목에 따라 유형 값이 중요하거나 중요하지 않을 수 있습니다.

업데이트 2: Robin van der Knaap이 댓글에서 제안한 것처럼, 그 중 하나.System.Security.Claims.AuthenticationTypes값이 적절할 수 있습니다.

var claimsIdentity = new ClaimsIdentity( claims, AuthenticationTypes.Password );

// and elsewhere in your application...
if (User.Identity.AuthenticationType == AuthenticationTypes.Password) {
    // ...
}

제공된 답변에는 어느 정도 타당성이 있지만 완전히 정확한 것은 아닙니다.문자열을 추가하는 것만으로 마법처럼 작동한다고 가정할 수는 없습니다.설명 중 하나에 명시된 대로 이 문자열은 열거형 중 하나와 일치해야 하며, 이 문자열은 OWIN 인증/권한 부여 미들웨어에 지정된 문자열과 일치해야 합니다.예를 들면...

public void ConfigureOAuth(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            OAuthAuthorizationServerOptions serverOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp = true,
                TokenEndpointPath = new Microsoft.Owin.PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                AuthenticationType = AuthenticationTypes.Password,
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                Provider = new AppAuthServerProvider()
            };


            app.UseOAuthAuthorizationServer(serverOptions);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                {
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
                    AuthenticationType = AuthenticationTypes.Password
                });            
        }

그러나 위의 시나리오에서는 크게 문제가 되지 않습니다.그러나 더 많은 인증/인가 수준을 사용하는 경우 클레임이 동일한 수준과 일치하는 클레임과 연결됩니다.AuthenticationType...또 다른 예는 쿠키 인증을 사용하는 경우입니다.

public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/auth/login")
            });
        }

어디에AuthenticationType쿠키의 이름을 설명합니다. 앱이 다른 공급자로부터 다른 쿠키를 얻었을 수 있기 때문에 사용자가 쿠키의 이름을 설정하는 것이 중요합니다.AuthenticationType올바른 쿠키에 연결하기 위해 클레임을 인스턴스화할 때

언급URL : https://stackoverflow.com/questions/20254796/why-is-my-claimsidentity-isauthenticated-always-false-for-web-api-authorize-fil

반응형