2015-09-16 18 views
2

我正在爲web api實施OAuth 2.0。最初,我想要允許的唯一授予類型是「密碼」,用於資源所有者密碼授予類型。未來,我可能會擴展到其他庫存授予類型,甚至可以建立自定義類型。爲了實現,我在我的Startup.cs類中創建了下面的代碼。我沒有指定授權端點,而只是一個令牌端點。使用OAuthAuthorizationServer定製允許的授權類型

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

    public void ConfigureAuth(IAppBuilder app) 
    { 

     var myOAuthServerProvider = new MyOAuthServerProvider(); 

     app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions 
     { 

      // mark true if you are not on https channel. This should never be true for Production. 
      AllowInsecureHttp = true, 

      //Enable a 60 minute expiration time. 
      AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(60), 

      // Allows the authorization server to alter the response coming out so it can report a 401. 
      AuthenticationMode = AuthenticationMode.Active, 

      // Provider needs to be the custom class that performs our authentication. 
      Provider = myOAuthServerProvider, 

      // This specifies the endpoint path where you can generate a token. 
      TokenEndpointPath = new PathString("/api/token"), 

     }); 
    } 
} 

對於MyOAuthServerProvider類,我應該從OAuthAuthorizationServerProvider繼承和重寫的具體方法,只允許授予類型我想啓用,或者我應該不是從從地上爬起來的IOAuthAuthorizationServerProvider接口實現MyOAuthServerProvider?

回答

2

只允許您想要的授權類型,它足以從OAuthAuthorizationServerProvider繼承。然後,你需要重寫兩個方法:

  • ValidateClientAuthentication - 以驗證請求的來源是註冊client_id
  • GrantResourceOwnerCredentials - 驗證您提供usernamepasswordgrant_type設置爲password

欲瞭解更多信息,這裏是個GrantResourceOwnerCredentials方法:

時令牌端點的請求用的 「密碼」,「grant_type」到達調用。當用戶將名稱和密碼憑證 直接提供到客戶端應用程序的用戶界面,並且客戶端應用程序 正在使用它們來獲取「access_token」和可選的「refresh_token」時,會發生這種情況。 如果Web應用程序支持資源所有者憑據授予類型 ,則必須根據情況驗證context.Username和context.Password。 要發出訪問令牌,必須使用新的 票證調用context.Validated,該票據包含關於應與關聯 與訪問令牌關聯的資源所有者的聲明。應用程序應採取適當的措施以確保端點不被惡意主叫方濫用。默認的 行爲是拒絕這種授權類型。

+0

謝謝!我是否也必須重寫GrantAuthorizationCode,GrantClientCredentials和GrantCustomExtension以引發異常或返回特定的內容以防止使用這些授予類型? – tarun713

+0

沒關係,只是在文檔中看到,這些函數的默認行爲是拒絕授予類型。我會接受你的回答。 – tarun713

+0

有沒有什麼方法可以通過編程方式設置'grant_type'而不是通過API? –

相關問題