2014-04-25 65 views
3

我一直在尋找ASP.NET身份驗證附帶的ASP.NET Web API默認項目,它使用Owin。我已經搜索了一下,看到Owin是爲了將應用與服務器分離開來的,並且它的功能基於一個Startup類,它真的會在項目中退出。然而,類被分成兩個文件,就是這樣Startup課程如何發揮作用?

public partial class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     ConfigureAuth(app); 
    } 
} 

public partial class Startup 
{ 
    static Startup() 
    { 
     PublicClientId = "self"; 

     UserManagerFactory =() => new UserManager<IdentityUser>(new UserStore<IdentityUser>()); 

     OAuthOptions = new OAuthAuthorizationServerOptions 
     { 
      TokenEndpointPath = new PathString("/Token"), 
      Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory), 
      AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), 
      AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), 
      AllowInsecureHttp = true 
     }; 
    } 

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 

    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; } 

    public static string PublicClientId { get; private set; } 

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     app.UseCookieAuthentication(new CookieAuthenticationOptions()); 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(OAuthOptions); 

     // Uncomment the following lines to enable logging in with third party login providers 
     //app.UseMicrosoftAccountAuthentication(
     // clientId: "", 
     // clientSecret: ""); 

     //app.UseTwitterAuthentication(
     // consumerKey: "", 
     // consumerSecret: ""); 

     //app.UseFacebookAuthentication(
     // appId: "", 
     // appSecret: ""); 

     //app.UseGoogleAuthentication(); 
    } 
} 

第一個文件,上面的名稱空間存在此行

[assembly: OwinStartup(typeof(WebApplication1.Startup))] 

現在這個類是用來只是在auth控制器上,但基本上它僅用於構建用戶管理器並獲取OAuthOptions.AccessTokenFormatPublicClientId信息。

在該設置中,該類僅用於提供這些信息。那麼,這個班級真的起作用了嗎?我真的不理解Owin和這個類之間的關係,它只是提供配置信息。

回答

6

您需要的組件添加到應用程序Owin管道來處理HTTP請求或什麼都不會發生:(

Owin使用的Convention over configuration軟件設計原則,認爲你的項目有一個名爲Startup類,它有一個方法名爲Configuration,它接受IAppBuilder類型的一個參數,它將在Owin應用程序管道中添加組件,其目的是讓程序員更快更輕鬆地進行設置,以便您可以花更多時間來創建您的API。

如果由於任何原因您不能按照Startup類約定確切地說,還有其他方法可以將Owin指向將代碼添加到Owin應用程序管道中的代碼。您已經確定了其中的一種方法:OwinStartup屬性。

[assembly: OwinStartup(typeof(WebApplication1.Startup))] 

您可以瞭解更多關於什麼OWIN啓動類不和它是如何檢測here