응용 기술 및 운영 정보:
프로그래밍 언어: C#
프런트엔드 측: WPF(Windows Presentation Foundation) - .NET Framework 4.6.1
백엔드 측: WCF(Windows Communication Foundation) - .NET Framework 4.6.1
선택한 프로젝트에서 필요한 패키지를 복원하고 PM 콘솔 에서 다음 명령을 실행합니다.
Update-Package -reinstall
이 응용 프로그램에서는 Enterprise Architecting 표준에서 WCF 서비스를 사용하여 권한 부여 및 인증을 사용하는 방법을 보여 드리겠습니다.
WCF
ASP.NET 인증 서비스
맞춤 인증
HTTP 쿠키
Authorization PrincipalPermission 속성
스레드 현재주체
메시지 인터셉터
WCF 서비스 응용 프로그램을 만듭니다.
ASP.NET 인증 서비스를 재사용하는 AuthenticationService.svc를 추가합니다.
사용자 유효성 검사기 클래스를 만듭니다.
Global.asax에서 사용자 정의 인증을 활성화합니다.
유효한 사용자인 경우 쿠키를 반환합니다.
서비스 구성을 수정합니다.
SumOperation, ReadOperation 및 WriteOperation이라는 세 가지 다른 메서드를 사용하여 ExecuteOperationsService.svc를 만듭니다.
승인된 액세스에 대해서만 PrincipalPermission 속성으로 서비스 메서드를 장식합니다.
AspNetCompatibilityRequirements 특성으로 ExecuteOperationsService 클래스를 장식합니다.
서버 애플리케이션에 인터셉터를 구현합니다.
서비스 애플리케이션의 인터셉터에 ID 설정 코드를 구현합니다.
이름 대신 역할을 포함하도록 서비스 측 코드를 수정합니다.
사용자 이름과 역할을 저장하려면 암호화된 티켓을 사용하세요.
클라이언트 애플리케이션을 생성하고 두 서비스에 대한 참조를 추가합니다.
클라이언트 애플리케이션에 인터셉터를 구현합니다.
인증 서비스 인스턴스를 만들고 Login() 메서드를 호출합니다.
쿠키를 받아 저장합니다.
ExecuteOperationsService 인스턴스를 생성하고 SumOperation, ReadOperation 및 WriteOperation을 호출합니다.
ExecuteOperationsService 클라이언트에 쿠키를 연결합니다.
1. ASP.NET 인증 서비스를 재사용하는 AuthenticationService.svc를 추가합니다.
새 WCF 서비스를 추가하고 이름을 AuthenticationService.svc로 지정합니다. ASP.NET 인증 서비스를 노출할 예정이므로 관련 파일을 삭제합니다.
AuthenticationService.cs 삭제
IAuthenticationService.cs 삭제
<%@ ServiceHost Language="C#" Service="System.Web.ApplicationServices.AuthenticationService" Factory="System.Web.ApplicationServices.ApplicationServicesHostFactory" %>
2. Global.asax에서 사용자 정의 인증을 활성화하고 유효한 사용자인 경우 쿠키를 반환합니다.
새 항목 웹 > 전역 애플리케이션 클래스를 프로젝트에 추가합니다.
protected void Application_Start(객체 전송자, EventArgs e) { AuthenticationService.Authenticating += AuthenticationService_Authenticating; }
개인 무효 AuthenticationService_Authenticating(개체 보낸 사람, AuthenticatingEventArgs e) { 문자열 역할 = 문자열.Empty; e.Authenticated = UserIsValid(e, 참조 역할); e.AuthenticationIsComplete = true; if (e.Authenticated) { string encryptedValue = FormsAuthentication.Encrypt(CreateFormsAuthenticationTicket(e,roles)); OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] = SetSetCookieInResponseChannelHeaders(encryptedValue); } }
이 메서드는 인증 이벤트 인수의 사용자 정의 자격 증명 개체에서 사용자 이름과 비밀번호를 추출합니다. 그런 다음 UserValidator 클래스를 사용하여 사용자 이름과 비밀번호의 유효성을 검사합니다.
Authenticated 속성은 사용자가 유효한지 여부에 따라 true/false를 나타냅니다.
3. 인증 서비스 및 ASP.NET 호환성 활성화
이제 다음을 포함하도록 web.config 파일을 수정해야 합니다.
인증 서비스 활성화
ASP.NET 호환성 활성화
<system.web.extensions> <스크립팅> <웹서비스> <authenticationService 활성화="true"/> </webServices> </스크립팅> </system.web.extensions>
4. 서버 애플리케이션에 인터셉터를 구현합니다.
이는 Operation Context에 쿠키를 첨부하는 위의 코드가 서비스 호출을 해야 할 때마다 지루한 작업처럼 보이기 때문입니다. WCF 인터셉터를 사용하여 이러한 작업을 백그라운드로 이동할 수 있습니다.
MSDN: WCF 데이터 서비스를 사용하면 애플리케이션이 요청 메시지를 가로채서 작업에 사용자 지정 논리를 추가할 수 있습니다. 이 사용자 지정 논리를 사용하여 수신 메시지의 데이터 유효성을 검사할 수 있습니다. 또한 요청별로 사용자 정의 권한 부여 정책을 삽입하는 등 쿼리 요청의 범위를 추가로 제한하는 데에도 사용할 수 있습니다.
다음은 이 단계와 관련된 활동입니다.
서버 web.config 내에 인터셉터 동작을 추가합니다.
인터셉터 동작 클래스를 만듭니다. (프로젝트에서 참조)
IdentityMessageInspector 클래스를 만듭니다. (프로젝트에서 참조)
<시스템.서비스모델> <서비스> <service name="AuthenticationAndAuthorization.ExecuteOperationsService" BehaviorConfiguration="InterceptorBehavior" /> </서비스> <행동> <서비스 동작> <행동> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> </행동> <behavior name="InterceptorBehavior"> <serviceDebug includeExceptionDetailInFaults="true" /> <interceptorBehaviorExtension /> </행동> </serviceBehaviors> </행동> <확장자> <동작 확장> <add name="interceptorBehaviorExtension" type="AuthenticationAndAuthorization.Extensions.IDispatchMessageInspector.InterceptorBehaviorExtension, AuthenticationAndAuthorization, Version=1.0.0.0, Culture=neutral"/> </behavior확장> </확장자> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel>
5. 쿠키 암호화.
당사의 쿠키에는 Fiddler와 같은 HTTP 검사 유틸리티로 쉽게 읽을 수 있는 정보가 포함되어 있습니다. 이로 인해 쿠키 정보가 보안 위협에 노출되기 쉽습니다.
FormsAuthenticationTicket : System.Web.Security 네임스페이스는 우리에게 편리한 클래스를 제공합니다. 이 클래스 인스턴스 내에 사용자 이름과 역할 정보를 저장할 수 있습니다. 티켓 클래스는 만료 및 암호화 기능도 제공합니다.
private FormsAuthenticationTicket CreateFormsAuthenticationTicket(AuthenticatingEventArgs e, stringroles) => new FormsAuthenticationTicket(1, e.UserName, DateTime.Now, DateTime.Now.AddHours(24), true,roles,FormsAuthentication.FormsCookiePath);
string 암호화된값 = FormsAuthentication.Encrypt(CreateFormsAuthenticationTicket(e, 역할)); 개인 FormsAuthenticationTicket GetDecryptTicket(stringcryptedTicket) => FormsAuthentication.Decrypt(encryptedTicket);
개인 HttpResponseMessageProperty SetSetCookieInResponseChannelHeaders(string cookieValue) { HttpResponseMessageProperty response = new HttpResponseMessageProperty(); response.Headers[HttpResponseHeader.SetCookie] = FormsAuthentication.FormsCookieName + "=" + cookieValue; 응답 반환; }
<인증 모드="양식"> <forms SlidingExpiration="true" name="AuthCookie" protection="All" timeout="20"/> </인증> <machineKey decryption="AES" 유효성 검사="SHA1" decryptionKey="1523F567EE75F7FB5AC0AC4D79E1D9F25430E3E2F1BCDD3370BCFC4EFC97A541" 유효성 검사Key="33CBA563F26041EE5B5FE9581076C40618DCC1218F5F447634EDE8624508A129"/>
6. 클라이언트 애플리케이션에 인터셉터를 구현합니다.
다음은 이 단계와 관련된 활동입니다.
Client App.config 내에 인터셉터 동작 추가
인터셉터 동작 클래스를 만듭니다. (프로젝트에서 참조)
CookieMessageInspector 클래스를 만듭니다. (프로젝트에서 참조)
<행동> <endpointBehaviors> <행동 이름 ="InterceptorBehavior"> <interceptorBehaviorExtension /> </행동> </endpointBehaviors> </행동>
<endpoint address="http://localhost:8046/ExecuteOperationsService.svc" 바인딩="basicHttpBinding" 바인딩Configuration="BasicHttpBinding_IExecuteOperationsService" contract="ExecuteOperationsServiceReference.IExecuteOperationsService" name="BasicHttpBinding_IExecuteOperationsService" BehaviorConfiguration="InterceptorBehavior"/>