.Net WebApi 實現OAuth2.0認證

如今多數公衆平臺提供的api都使用OAuth2.0認證模式,最近在搞Android方面的開發,身份認證和權限控制的各方面比較來講,使用OAuth認證的仍是比較靠譜,OAuth2.0的協議能夠參考https://tools.ietf.org/html/rfc6749。html

微信Katana項目實現了OWIN的一系列接口,其中實現OAuth認證主要用到這三個類庫Microsoft.Owin,Microsoft.Owin.Security,Microsoft.Owin.Security.OAuth,其中官方實現了Bearer Token的認證方式,這個是twitter使用的認證模式,能夠參考 RFC 6750: The OAuth 2.0 Authorization Framework: Bearer Token Usageapi

基於Owin搭建中間件的方式,Bearer Token的實現包括三個類,OAuthBearerAuthenticationHandler、OAuthBearerAuthenticationMiddleware、OAuthBearerAuthenticationOptions,有興趣的朋友能夠本身擴展實現其餘的認證方式,如微信api那種類型的,把token放在查詢參數中或者Post的表單裏的。微信

配置身份認證的詳細信息,能夠參考官方文檔 http://go.microsoft.com/fwlink/?LinkId=301864cookie

(1) 配置應用程序架構

在Startup.cs,配置使用BearerToken認證模式,TokenEndpointPath是獲取Token的路徑,Provider配置IOAuthAuthorizationServerProvider接口的實現類處理權限認證過程的各類事件(包括token請求、認證請求、驗證認證等)。app

public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                //在生產模式下設 AllowInsecureHttp = false
                AllowInsecureHttp = true                
            };

            // 使應用程序能夠使用不記名令牌來驗證用戶身份
            app.UseOAuthBearerTokens(OAuthOptions);

(2)配置Provide,建一個類繼承 OAuthAuthorizationServerProvider,這個類已經實現了大部分功能,咱們如今須要作的是用戶認證部分,經過重載GrantResourceOwnerCredentials獲取用戶名和密碼進行認證。async

    public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
    {
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();

            ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "用戶名或密碼不正確。");
                return;
            }

            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
               OAuthDefaults.AuthenticationType);
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
                CookieAuthenticationDefaults.AuthenticationType);

            AuthenticationProperties properties = CreateProperties(user.UserName);
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
            context.Validated(ticket);
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }
    }

 這樣整個OAuth2.0的認證架構就搭起來了,後面再介紹怎麼使用網頁和Android獲取token及訪問數據。ide

 

夢秋 2016-07-19spa

相關文章
相關標籤/搜索