2017-08-16 81 views
0

的情況是很簡單的 我使用的是自定義登錄爲簡單起見,以生成角度我已經做了我在谷歌的研究承載的道理,但我不知道爲什麼沒有在這個問題上承載令牌在asp.net網頁API角

下面

簡單的例子是代碼:

public class IdentityController : ApiController 
    { 
     IdentityController() 
     { 
      OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); 
     } 
     public static OAuthBearerAuthenticationOptions OAuthBearerOptions { get; private set; } 
     [HttpPost] 
     public IHttpActionResult login([FromBody]LoginModel user) 
     { 
      var username = user.Username.ToLower(); 
      var password = user.Password; 

      if (username == "admin" && password == "1234") 
      { 
       var identity = new ClaimsIdentity(username); 
       identity.AddClaim(new Claim(ClaimTypes.Name, username)); 
       var principal = new ClaimsPrincipal(identity); 
       Thread.CurrentPrincipal = new ClaimsPrincipal(principal); 
       if (HttpContext.Current != null) 
       { 
        HttpContext.Current.User = principal; 
       } 

       var ticket = new AuthenticationTicket(identity, new AuthenticationProperties()); 
       var currentUtc = new SystemClock().UtcNow; 
       ticket.Properties.IssuedUtc = currentUtc; 
       ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(30)); 



       FormsAuthentication.SetAuthCookie(username , false); 
       var result = new { authenticatonToke = OAuthBearerOptions.AccessTokenFormat.Protect(ticket) }; 
       return Ok(result); 
      } 

      else return BadRequest("wrong user name or password"); 
     } 

    } 

我得到

OAuthBearerOptions.AccessTokenFormat.Protect(ticket) 

空引用錯誤,因爲我AccessTokenFormat小號空

有沒有其他的解決辦法可能產生的Web API承載令牌? 我不希望使用asp.net身份或任何其他事情..只是,如果admin,密碼爲1234。當我得到的承載標記我想在郵遞員用它

+0

此:http://odetocode.com/blogs/scott/archive/2015/01/15/using-json-web-tokens-with-katana-and-webapi.aspx可能會幫助您設置AccessTokenFormat – jps

回答

0

我會強烈建議您使用Identity Server生成令牌,管理用戶/客戶端等,您也可以在此page

找到幾個的OpenID認證解決方案

聯邦安全是一個重要的課題。內部解決方案可能與第三方存在問題。

+0

我知道,這僅僅是爲了測試。安全不在我正在建設的應用範圍內。 – Arash

+0

這可能是值得花一些時間相應Github頁面上。 TokenResponseGenerator.cs可能對您的問題有所幫助。 – zapoo

+0

[此庫](https://github.com/dvsekhvalnov/jose-jwt)也可以幫助您創建加密的令牌。 – zapoo