웹 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
'programing' 카테고리의 다른 글
두 인수 중 하나가 NaN인 경우 C/C++ <, <= 및 == 연산자가 true를 반환하는 원인은 무엇입니까? (0) | 2023.06.10 |
---|---|
명령줄을 사용하여 Firebase 데이터베이스 보안 규칙을 배포하는 방법은 무엇입니까? (0) | 2023.06.10 |
Firestore 문서에 타임스탬프 추가 (0) | 2023.06.10 |
마우스 클릭 없이 Excel에서 하이퍼링크를 여는 방법, 바로 가기 키/키가 있습니까? (0) | 2023.06.10 |
ND에서 1D 어레이까지 (0) | 2023.06.10 |