3

우리는 ajax 호출을 위해 단일 페이지 응용 프로그램 및 웹 API를 제공하기 위해 MVC를 사용하는 ASP.NET으로 작성된 웹 응용 프로그램을 보유하고 있습니다.ASP.NET에서 토큰 기반 인증으로 쿠키 바꾸기 OWIN OpenIdConnect 코드 인증 흐름

는 인증 기관에 대한 애저 AD와 Microsoft.OwinOpenIdConnect를 이용한다. OAUTH 흐름은 서버 측 코드 권한입니다. 다음 Startup.Auth.cs 에서 우리는이

public void ConfigureAuth(IAppBuilder app) 
    { 
     app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); 
     var cookieAuthenticationOptions = new CookieAuthenticationOptions() 
     { 
      CookieName = CookieName, 
      ExpireTimeSpan = TimeSpan.FromDays(30), 
      AuthenticationType = CookieAuthenticationDefaults.AuthenticationType, 
      SlidingExpiration = true, 
     }; 
     app.UseCookieAuthentication(cookieAuthenticationOptions); 
     app.UseOpenIdConnectAuthentication(
      new OpenIdConnectAuthenticationOptions 
      { 
        AuthorizationCodeReceived = (context) => 
        { 
         /*exchange authorization code for a token 
         stored on database to access API registered on AzureAD (using ADAL.NET) */ 
        }, 

        RedirectToIdentityProvider = (RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context) => 
        { 
         /* Set the redirects URI here*/ 
        }, 
      }); 
    } 

우리가 그 루트 그런 다음 MVC 컨트롤러

public class AccountController : Controller 
{ 
    public void SignIn(string signalrRef) 
    { 
     var authenticationProperties = /* Proper auth properties, redirect etc.*/ 
     HttpContext.GetOwinContext() 
      .Authentication.Challenge(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); 
    } 

    public void SignOut(string signalrRef) 
    { 
     var authenticationProperties = /* Proper auth properties, redirect etc.*/ 
     HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, 
      OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType); 
    } 

의 메소드 년말에 매핑 URL로 이동 로그인 절차 클릭하면 사용자가 우리의 응용 프로그램에 연결하면 ASP.NET 쿠키를 사용하여 클라이언트 응용 프로그램과 ASP.net 서버간에 인증됩니다. 대신 토큰 기반 접근 방식을 사용하고 싶습니다. 관심이 있으시면 this is the reason.

제가

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

의해 Microsoft.Owin.Security.Cookies

app.UseCookieAuthentication(cookieAuthenticationOptions); 교체 Microsoft.Owin.Security.OAuth 의해 Startup.cs 에 에게 Nuget 패키지를 대체하려고 내 계정 관리자에서 도전 과제를 HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, CookieAuthenticationDefaults.AuthenticationType);에서 HttpContext.GetOwinContext().Authentication.SignOut(authenticationProperties, OpenIdConnectAuthenticationDefaults.AuthenticationType, OAuthDefaults.AuthenticationType);

으로 변경했습니다.

문제는 쿠키를 사용하면 쿠키 세트이 웹 요청에서 자동으로 전송되었으므로 지정한 URL로 리디렉션되는 동안 플로우가 완료되면 응답합니다. 내가 UseOAuthBearerAuthentication와 OWIN에 의해 ​​생성 된 무기명을 찾을 수 있습니다 (이 경우) **, ** 어디에서 내 클라이언트 SPA를 다시

주를 보내야 할 때 :의 오픈 소스 샘플을 우리가하려는 일은 this github repository에서 찾을 수 있습니다.

답변

2

나는 두 가지 접근법을 고려해야한다고 생각합니다.

  1. 자바 스크립트 라이브러리를 사용하여 단일 페이지 응용 프로그램 내에서 로그인 & 토큰을 수집합니다. 그런 다음 백엔드는 순전히 웹 API이며 OAuth 베어러 미들웨어를 사용하여 요청을 인증 할 수 있습니다. 백엔드는 사용자 로그인에 대해 아무것도 모릅니다. 우리는이 접근 방식을 취하는 좋은 샘플을 가지고 있습니다. here. 백엔드에서 API 호출을해야하는 경우 OnBehalfOf 플로우도 고려할 수 있습니다. 나는이 방법을 권장한다.
  2. 서버의 OpenIDConnect 미들웨어를 사용하여 사용자 로그인 및 토큰 획득을 수행하십시오. CookieAuthenticationMiddleware의 사용을 완전히 생략 할 수도 있습니다 (100 % 확실하지는 않지만). 언급 한대로 AuthorizationCodeReceived 알림에 토큰을 캡처 할 수 있으며 URL 단편에 토큰이있는 SPA로 다시 리디렉션 할 수 있습니다. 토큰 (서버에 캐시 됨)을 자바 스크립트로 전달하는 경로가있을 수도 있습니다. 두 경우 모두 외부 발신자가 토큰에 액세스 할 수 없도록해야합니다.

염두에 두어야 할 점은 토큰이 만료 될 때 새로 고치는 방법입니다. # 1을 사용하면 대부분이 라이브러리에 의해 처리됩니다. # 2를 사용한다면 직접 관리해야합니다.

+1

비토리오 (Vittorio)도 # 2와 함께 도움이 될 훌륭한 기사를 가지고 있습니다. http://www.cloudidentity.com/blog/2014/04/28/use-owin-azure-ad-to-secure-both-mvc -ux-and-web-api-in-the-same-project/ – dstrockis

+0

thx! 내가 틀렸다면. Opt1, 100 % 암시 적 흐름은 적응되지 않습니다. 우리는 제 3의 api 요청 (사무실 365 그래프 등)에 우리의 논리로 '합류'하기위한 많은 서버 논리를 가지고 있으며 우리는 또한 데몬 (deamons)을 가지고 있습니다. OnBehalfOf는 우리가 필요로하지만 Azure ADv2.0에서 아직 지원되지 않는 것 같습니다. 우리는 지금 v2.0으로 이동하려고합니다 ... Opt2에서, 다음과 같은 사이에 방출 된 동일한 JWT를 재사용 할 것을 제안합니다. AzureAD와 내 서버는 내 클라이언트와 내 서버 사이에서 권한을 부여합니까? 사실 저는 라이브러리가 단지 ASP.NET이 기존의 오래된 쿠키 대신 토큰을 낼 수 있기를 바랬습니다. –

+1

아하이 봐요. 예, v2의 OBO는 아직 없습니다. 죄송합니다. 당신은 # 2에 대한 설명에서 정확합니다. 귀하의 제안도 좋습니다 ... AAD 토큰을 사용하여 클라이언트와 서버의 상호 작용을 승인하는 대신, AAD 토큰을 사용하여 자신의 유형의 토큰을 초기화하고 대신 사용할 수 있습니다. JWT를 생성하는 데 도움이되는 몇 가지 오픈 소스 라이브러리가 있으며, 그 중 하나를 사용할 수 있습니다. # 2는 암호화와 함께 제공되는 키 관리를 포함하여 사용자가 그렇게하지 않아도되게합니다. – dstrockis