2017-07-17 186 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; 
相关问题