programing

OWIN / Katana를 사용하여 Azure에서 데이터 보호 작업에 실패했습니다.

elecom 2023. 5. 8. 21:54
반응형

OWIN / Katana를 사용하여 Azure에서 데이터 보호 작업에 실패했습니다.

OWIN/Katana 기반 ASP에서 비밀번호 재설정을 구현하려고 합니다.Azure에서 실행 중인 NET MVC 웹사이트.

로컬에서 실행할 때는 정상적으로 작동하지만 프로덕션에서는 실패합니다.

사용자 토큰 공급자 생성

userManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("PasswordReset"))

하지만 다음과 같이 토큰을 생성하려고 할 때

var resetToken = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

다음과 같은 예외가 있습니다.

시스템, 보안암호학.암호화 예외:데이터 보호 작업에 실패했습니다.이 문제는 현재 스레드의 사용자 컨텍스트에 대한 사용자 프로필이 로드되지 않았기 때문일 수 있습니다. 스레드가 가장하는 경우일 수 있습니다.시스템에서.보안.암호학.보호된 데이터.시스템에서 Protect(Byte[] userData, Byte[] 옵션인 Entropy, Data Protection Scope 범위).보안.암호학.Dpapi DataProtector입니다.시스템에서 공급자 보호(바이트[] 사용자 데이터)입니다.보안.암호학.데이터 보호기.Microsoft에서 보호(Byte[] 사용자 데이터).오윈. 보안.데이터 보호.Dpapi DataProtector입니다.Microsoft에서 보호(Byte[] 사용자 데이터).애스넷. 아이덴티티.Owin.DataProtector토큰 제공자 2.d__0.MoveNext() --- 시스템에서 예외가 발생한 이전 위치의 스택 추적 끝.런타임.컴파일러 서비스.작업 대기자입니다.시스템에서 성공하지 못한 경우(작업 작업)를 던집니다.런타임.컴파일러 서비스.작업 대기자입니다.Microsoft에서 NonSuccessAndDebuggerNotification(작업 작업)을 처리합니다.애스넷. 아이덴티티.사용자 관리자 2.d__e9.다음으로 이동()

호스트 서버가 가상 시스템인 경우 오류 메시지에 정확히 표시될 수 있습니다.에 정말로 IIS가 하십시오.Load User Profile예외가 말하는 것처럼 true로 설정됩니다.

  • [연결] 영역에서 서버 이름을 펼친 후 [애플리케이션 풀]을 누릅니다.
  • 자신의 풀을 마우스 오른쪽 버튼으로 클릭합니다.
  • 고급 설정

여기에 이미지 설명 입력

ASP로 토큰을 생성하려고 할 때도 같은 문제가 발생합니다.웹 API의 Net ID 및 사용자 정의 로그인 기능입니다.

"데이터 보호 작업에 실패했습니다.이는 현재 스레드의 사용자 컨텍스트에 대한 사용자 프로필이 로드되지 않았기 때문일 수 있습니다. 스레드가 가장하는 경우일 수 있습니다."

가 한 " 프로그램 "을 만든 입니다.WEBSITE_LOAD_USER_PROFILEMicrosoft Azure는 1번째 버전입니다.그 해결책은 저에게 효과가 있습니다.

자세한 내용은 여기에서 확인할 수 있습니다.

이 질문에 대한 의 답변을 봐주세요.훨씬 더 간단한 솔루션은 다음을 활용하여 달성할 수 있습니다.IAppBuilder.GetDataProtectionProvider()

해결책을 찾았어요모든 단계가 필요한지는 정확히 알 수 없지만, 이제는 앱이 완벽하게 작동합니다.

1.- 보안을 지원하도록 web.config를 업데이트합니다.토큰 핸들러

<section name="system.identityModel" type="System.IdentityModel.Configuration.SystemIdentityModelSection, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
<section name="system.identityModel.services" type="System.IdentityModel.Services.Configuration.SystemIdentityModelServicesSection, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

설정할 수 있습니다.그리고.

  <securityTokenHandlers>
    <remove type="System.IdentityModel.Tokens.SessionSecurityTokenHandler,
                System.IdentityModel, Version=4.0.0.0, Culture=neutral,
                PublicKeyToken=B77A5C561934E089" />

    <add
      type="System.IdentityModel.Services.Tokens.MachineKeySessionSecurityTokenHandler,
          System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral,
          PublicKeyToken=B77A5C561934E089">
      <sessionTokenRequirement lifetime="00:30:00"></sessionTokenRequirement>
    </add>
  </securityTokenHandlers>

</identityConfiguration>

일반 노드로. 2. - 스타트업에서.Auth.cs 파일에서 ConfigureAuth(IAppBuilder 앱)를 다음과 같이 업데이트합니다.

public void ConfigureAuth(IAppBuilder app)
        {

            UserManagerFactory = () =>
            {
                var userManager = new UserManager<SIAgroUser>(new UserStore<UserType>(new SIAgroUserDbContext()));

                IDataProtectionProvider provider = app.GetDataProtectionProvider();

                //userManager.UserTokenProvider = new Microsoft.AspNet.Identity.Owin.DataProtectorTokenProvider<UserType>(provider.Create("PasswordReset") );
                if (provider != null)
                {
                    userManager.UserTokenProvider = new DataProtectorTokenProvider<UsertType, string>(provider.Create("PasswordReset"));
                }

                return userManager;
            };

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            //app.UseFacebookAuthentication(
            //    appId: "",
            //    appSecret: "");

            //app.UseGoogleAuthentication();



        }

3.- Startup 클래스의 생성자를 다음과 같이 정리합니다.

static Startup()
{
   PublicClientId = "self";
}

그것은 나에게 효과가 있었습니다 :) 당신에게도 효과가 있기를 바랍니다.

이 오류는 공유 호스팅 공급자의 다음 행에서 발생합니다.

var provider = new DpapiDataProtectionProvider("SITENAME");

해결책은 매우 간단했습니다.먼저 위의 행을 다음과 같이 변경합니다.

var provider = new MachineKeyProtectionProvider();

그런 다음 유틸리티 네임스페이스에 있는 다음과 같은 새 파일을 만듭니다.

using Microsoft.Owin.Security.DataProtection;
using System.Web.Security;

namespace <yournamespace>.Utilities
{
    public class MachineKeyProtectionProvider : IDataProtectionProvider
    {
        public IDataProtector Create(params string[] purposes)
        {
            return new MachineKeyDataProtector(purposes);
        }
    }

    public class MachineKeyDataProtector : IDataProtector
    {
        private readonly string[] _purposes;

        public MachineKeyDataProtector(string[] purposes)
        {
            _purposes = purposes;
        }

        public byte[] Protect(byte[] userData)
        {
            return MachineKey.Protect(userData, _purposes);
        }

        public byte[] Unprotect(byte[] protectedData)
        {
            return MachineKey.Unprotect(protectedData, _purposes);
        }
    }
}

해결되었습니다.문제는 해결됐습니다.암호 재설정 컨트롤러 방법에서는 이 공급자도 사용해야 합니다. 그렇지 않으면 다음 메시지가 표시됩니다.Invalid Tokenmessage

저는 잠시 동안 이것을 얼음 위에 올려놓았지만, 어쩔 수 없이 다시 그것으로 돌아왔습니다.여기서 해결 방법을 찾았습니다: Azure 웹 사이트에서 암호 재설정 토큰을 생성할 수 없습니다.

App_Start/Startup에 설정된 대로 Owin 파이프라인에서 UserManager를 가져옵니다.Auth.cs , Azure에서 작동합니다.저는 이것이 구체적으로 어떻게 작동하는지 잘 모르겠습니다.DpApi는 첫 번째 링크에 설명된 솔루션과 함께 Azure에서 작동해야 합니다.

DpApi에 Web.config에 정적 시스템 키가 설정되어 있으면 모든 서버 시스템이 웹 팜의 다른 시스템에서 생성한 암호화된 데이터를 해독할 수 있습니다.

(표준 템플릿에 지정된 코드 - AccountController.cs 에서 제공)

 private UserManager userManager;
    public UserManager UserManager
    {
        get { return userManager ?? HttpContext.GetOwinContext().GetUserManager<UserManager>(); }
        private set { userManager = value; }
    }

저와 다른 두 사람이 며칠 동안 이 오류를 처리한 후 IIS에서 흥미로운 것을 발견했습니다.사용자 프로파일 로드가 전환되면 applicationhost.config에 다음이 생성됩니다.

loadUserProfile="true"

하지만 당신이 그것을 끌 때 그것은 또한 작동하지만, 지금은 라인.

loadUserProfile="false"

추가되었습니다.따라서 기본값을 applicationhost.config에 기록해야 작동할 수 있다는 차이점이 다릅니다.일부 캐시가 다시 생성됩니까?

언급URL : https://stackoverflow.com/questions/23773651/the-data-protection-operation-was-unsuccessful-on-azure-using-owin-katana

반응형