ProgramingTip

내 ClaimsIdentity IsAuthenticated가 항상 거짓 인 이유는 무엇입니까 (웹 API 승인 필터의 경우)?

bestdevel 2020. 11. 17. 20:40
반응형

내 ClaimsIdentity IsAuthenticated가 항상 거짓 인 이유는 무엇입니까 (웹 API 승인 필터의 경우)?


Web 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를 구성하고 슬롯에 할당했는데 사용자가 인증하지 않았다고 생각하는 이유는 무엇입니까?


문제는 .Net 4.5의 주요 변경 사항 때문입니다. 이 문서 에서 설명했듯이 클레임 ID를 구성해도 더 이상 IsAuthenticated가 사실입니다. 대신 생성자에 품번 (무엇이든 상관 없음)을 전달해야합니다.

따라서 위 코드 에서이 줄 :

var claimsIdentity = new ClaimsIdentity( claims );

이렇게됩니다 :

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

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

업데이트 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 / 권한 부여 미들웨어에 지정된 것과 일치해야합니다 ....를 들어 ...AuthenticationTypes

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

반응형