2017-06-14 105 views
0

我正在嘗試使用MSAL保護Web API 2。 我的認證客戶端工作,我得到一個有效的令牌(用jwt.io驗證)。HTTP請求沒有命中WEB API 2控制器

我有一個Web API 2這樣配置:

的配置的WebAPI:

public static void Register(HttpConfiguration config) 
{ 
    config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.All; 
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
    config.EnableCors(); 
    config.MapHttpAttributeRoutes(); 
    config.Routes.MapHttpRoute(
     name: "DefaultApi", 
     routeTemplate: "api/{controller}/{id}", 
     defaults: new { id = RouteParameter.Optional } 
     ); 
} 

我Startup.Auth.cs看起來是這樣的:

 public void ConfigureAuth(IAppBuilder app) 
    { 
     string clientId = "the_client_id"; 

     var tokenValidationParameters = new TokenValidationParameters 
     { 
      ValidAudience = clientId, 
      ValidateIssuer = false 
     }; 
     Debug.WriteLine("Client ID = " + tokenValidationParameters.ValidAudience); 
     app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions 
     { 
      AccessTokenFormat = new Microsoft.Owin.Security.Jwt.JwtFormat(tokenValidationParameters, new OpenIdConnectCachingSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")) 
     }); 
    } 

和簡單的控制器:

[Authorize] 
[EnableCors(origins: "*", headers: "*", methods: "*")] 
public class BundlesController : ApiController 
{ 
    private APIContext db = new APIContext(); 

    // GET: api/Bundles 
    public IQueryable<Bundles> GetBundles() 
    { 
     Claim subject = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier); 
     db.Configuration.ProxyCreationEnabled = false; 
     return db.Bundles.Include(x => x.Products.Select(y => y.Defects)); 
    } 

在添加[Authorize]屬性之前,API像魅力一樣工作並正確返回數據。

如果我在控制器的GET函數中設置了一個斷點,它不會被擊中,我會得到一個401:授權已被拒絕。 我很確定我在apps.dev.microsoft.com上正確註冊了我的應用程序。

我不明白我的API在什麼時候阻止了這些調用。 任何建議,非常感謝!

謝謝!

回答

0

所以,對於這種干擾感到抱歉!

我的問題是,我是從App調用這樣令牌方法:

App.IdentityClientApp.AcquireTokenAsync(new String[] { premissionScopes }); 

當我應該做的

App.IdentityClientApp.AcquireTokenAsync(new String[] { Constants.ApplicationID }); 

所以是的,你應該得到的第一個令牌與應用程序ID相關聯,然後將範圍提供給靜默令牌獲取方法。

0

嗨,你可以請嘗試添加支持證書:真正你的cors ?. 所以你EnableCors屬性會是這個樣子

EnableCors [origin:*,headers:*,methods:*,supportsCredentials:true] 

希望這有助於。

感謝, Bhadhri

2

我只是測試你的代碼都在我的本地和Azure的Web應用程序。一切正常。添加[Authorize]屬性後可以訪問API。

我的認證客戶端工作,我得到一個有效的令牌(用jwt.io驗證)。

令牌將過期取決於JWT的exp屬性。默認情況下,它將在60分鐘內過期。嘗試重新生成令牌並使用它來訪問您的Web API。

+0

謝謝你的回答。 我在每次調用API之前調用AcquireTokenSilentAsync。 如果我理解正確,我應該得到一個令牌並延長到期日期。無論如何,出於測試目的,我每次都登錄,因此到期不應該成爲問題。 –

+0

我得到的令牌是這樣的: AcquireTokenAsync(new String [] {「User.Read」})並將其更改爲AcquireTokenAsync(new String [] {applicationID}) 它似乎工作。你認爲這個問題來自這裏嗎? –

+1

是的。這就是原因。根據官方示例,applicationID是必需的。 – Amor