2014-11-17 3 views
16

Owin 및 ASP.NET ID를 사용하여 웹 API 메서드를 보안하기 위해 OAuth 토큰을 사용하고 있습니다. 토큰 하위 시스템은 다음과 같이 설정됩니다.컨트롤러에 토큰 생성

var oauthOptions = new OAuthAuthorizationServerOptions() 
{ 
    TokenEndpointPath = new PathString("/Token"), 
    Provider = new SimpleAuthorizationServerProvider(), 
    AccessTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Access_Token", "v1")), 
    RefreshTokenFormat = new TicketDataFormat(app.CreateDataProtector(typeof(OAuthAuthorizationServerMiddleware).Namespace, "Refresh_Token", "v1")), 
    AccessTokenProvider = new AuthenticationTokenProvider(), 
    RefreshTokenProvider = new AuthenticationTokenProvider(), 
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
    AllowInsecureHttp = true 
}; 

app.UseOAuthAuthorizationServer(oauthOptions); 
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 

사용자 이름/암호를 기반으로 토큰을 요청한 다음 해당 토큰을 소비하는 데 유용합니다. 그러나 SPA를 렌더링하는 컨트롤러를 때면 사용자가 이미 인증 되었기 때문에 내보기에서 토큰을 생성하고 SPA에 다시 로그인하지 않고 Javascript 코드로 전달하려고합니다.

제 질문은 : 수동으로 내 토큰을 생성하여 SPA보기에 포함시킬 수 있습니까?

답변

41

당신은 OAuthBearerOptions.AccessTokenFormat.Protect(ticket)를 호출하여 컨트롤러 내부의 액세스 토큰을 생성 할 수 있으며, 코드가 아래로 보일 것이다 :

 private JObject GenerateLocalAccessTokenResponse(string userName) 
    { 

     var tokenExpiration = TimeSpan.FromDays(1); 

     ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType); 

     identity.AddClaim(new Claim(ClaimTypes.Name, userName)); 

     var props = new AuthenticationProperties() 
     { 
      IssuedUtc = DateTime.UtcNow, 
      ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration), 
     }; 

     var ticket = new AuthenticationTicket(identity, props); 

     var accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket); 

     JObject tokenResponse = new JObject(
            new JProperty("userName", userName), 
            new JProperty("access_token", accessToken), 
            new JProperty("token_type", "bearer"), 
            new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()), 
            new JProperty(".issued", ticket.Properties.IssuedUtc.ToString()), 
            new JProperty(".expires", ticket.Properties.ExpiresUtc.ToString()) 
    ); 

     return tokenResponse; 
    } 

그리고 수업 시간에 당신에게

Startup.cs을 OAuthBearerOptionsstatic 재산을 선언해야 그러나 사용자가 다시 로그인하도록 요청하지 않고 액세스 토큰에 대한 자동 새로 고침을 구현하려는 경우 새로 고침 토큰 부여를 구현하는 것을 고려해야합니다. 제안한 방식대로 수행하지 마십시오. AngularJS로 작성된 SPA에서 새로 고침 토큰을 생성하는 방법에 대한 자세한 내역 blog post을 읽을 수 있습니다.

희망 사항. 질문에 대한 답변입니다.

+1

ASP.NET 웹 API 2에서는 이미 정적이며 이제는 'OAuthBearerOptions'에서'OAuthOptions'로 바뀌 었으므로 이제는 'Startup.OAuthOptions.AccessTokenFormat.Protect (티켓)'로 바뀌 었습니다. – Fred

+1

'ExpiresUtc' 속성을'Startup.OAuthOptions.AccessTokenExpireTimeSpan'으로 설정할 수 있습니다. – Fred

+3

컨트롤러를 통해 새로 고침 토큰을 생성하는 방법은 무엇입니까? –