2017-07-17 147 views
2

我試圖在web api上登錄用戶而不使用他們的用戶名/密碼組合。我有權訪問用戶的用戶對象,但需要「登錄」並將訪問令牌返回給客戶端應用程序以用於後續請求。WebAPI獲取訪問令牌沒有用戶名和密碼

我已經試過上的變化以下,但沒有運氣,在UserManager對象,只要我打電話GenerateUserIdentityAsync第一次導致它失敗的cookiesIdentity及其警告我佈置我投OAuthGrantResourceOwnerContextCredentials是「可疑類型轉換或檢查「,但代碼永遠無法到達該行;這是我試過的,這是從我的ApplicationOAuthProvider類的GrantResourceOwnerCredentials方法中得到並修改的。順便說一下,我的令牌終點完全符合通常的usernamepasswordgrant_type請求。

var user = // Super secret way of getting the user....; 
Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); 
// UserManager is not null at this point 
var oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, 
       OAuthDefaults.AuthenticationType); 
// UserManager is null at this point and so throws exception 
var cookiesIdentity = await user.GenerateUserIdentityAsync(UserManager, 
       CookieAuthenticationDefaults.AuthenticationType); 

var properties = ApplicationOAuthProvider.CreateProperties(user.UserName); 
var ticket = new AuthenticationTicket(oAuthIdentity, properties); 


((OAuthGrantResourceOwnerCredentialsContext)HttpContext.Current.GetOwinContext().Request.Context) 
      .Validated(ticket); 
     HttpContext.Current.GetOwinContext().Request.Context.Authentication.SignIn(cookiesIdentity); 

實質上所有我想要做的就是返回一個訪問令牌,對此我沒有用戶名和密碼,但一個「祕密」,我想,而不是使用用戶名密碼的用戶。有沒有辦法?

回答

1

行,所以經過一番挖掘,我發現this article,幫助我一起把這個代碼,就像一個魅力:

var user = // Super secret method of getting the user 
var tokenExpiration = TimeSpan.FromDays(1); 
ClaimsIdentity identity = new ClaimsIdentity(OAuthDefaults.AuthenticationType); 
identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); 
identity.AddClaim(new Claim("role", "user")); 
var props = new AuthenticationProperties() 
{ 
    IssuedUtc = DateTime.UtcNow, 
    ExpiresUtc = DateTime.UtcNow.Add(tokenExpiration), 
}; 
var ticket = new AuthenticationTicket(identity, props); 
var accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); 
JObject tokenResponse = new JObject(
    new JProperty("userName", user.UserName), 
    new JProperty("access_token", accessToken), 
    new JProperty("token_type", "bearer"), 
    new JProperty("expires_in", tokenExpiration.TotalSeconds.ToString()), 
    new JProperty(".issued", 
     ticket.Properties.IssuedUtc.GetValueOrDefault().DateTime.ToUniversalTime()), 
    new JProperty(".expires", 
     ticket.Properties.ExpiresUtc.GetValueOrDefault().DateTime.ToUniversalTime())); 
return tokenResponse; 
相關問題