2017-08-16 83 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