2017年10月18日 星期三

OWIN OAuth 驗證

之前就知道OWIN,但一直沒有特別去了解它,難得可以在專案上使用,於是就爬文來練習看看囉:)


建立一個空的Web API專案

需要安裝的NuGet Package


  • Owin
  • Microsoft.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.OAuth
  • Microsoft.Owin.Security.Cookies

建立 Startup.cs













設置OAuth

var option = new OAuthAuthorizationServerOptions();
// 取得token的網址
option.TokenEndpointPath = new PathString("/Token");
// Token過期時間
option.AccessTokenExpireTimeSpan = TimeSpan.FromDays(2);
// 是否允許使用Http
option.AllowInsecureHttp = true;
// 驗證使用者的Provider可覆寫OAuthAuthorizationServerProvider自定義Provider
option.Provider = new ApplicationAuthorizationServerProvider();
// 使用AuthorizationServer
 app.UseOAuthAuthorizationServer(option);
//使用Bearer驗證
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

覆寫OAuthAuthorizationServerProvider

覆寫ValidateClientAuthentication、GrantResourceOwnerCredentials
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
   // 因為覆寫自己想要的provider,所以先通過驗證以方便測試
   context.Validated();

   eturn Task.FromResult<object>(null);
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
 // 驗證user logic(先簡單驗證)
 if (context.UserName == "Tim" && context.Password == "123456")
 {
  // 建立身分要求
  var identity = new ClaimsIdentity(context.Options.AuthenticationType);
  // 新增ClaimTypes
  identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
  identity.AddClaim(new Claim(ClaimTypes.OtherPhone, "123456"));
  // 登入
  context.Request.Context.Authentication.SignIn(identity);
  // 驗證通過
  context.Validated(new AuthenticationTicket(identity, null));
 }
 else
 {
  context.SetError("invalid_grant", "The user name or password is incorrect.");
 }

 return Task.FromResult<object>(null);
}


POSTMAN測試(產生Token)

grant_type=password





















利用範本的API加上Authorize試試看Token驗證








先傳沒有Token測試一次(401)

















傳入Token(200)

















以上是透過簡單的方式產生Token,但還有一些細節沒有帶到,下一篇繼續研究


沒有留言:

張貼留言