我正在嘗試使用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在什麼時候阻止了這些調用。 任何建議,非常感謝!
謝謝!
謝謝你的回答。 我在每次調用API之前調用AcquireTokenSilentAsync。 如果我理解正確,我應該得到一個令牌並延長到期日期。無論如何,出於測試目的,我每次都登錄,因此到期不應該成爲問題。 –
我得到的令牌是這樣的: AcquireTokenAsync(new String [] {「User.Read」})並將其更改爲AcquireTokenAsync(new String [] {applicationID}) 它似乎工作。你認爲這個問題來自這裏嗎? –
是的。這就是原因。根據官方示例,applicationID是必需的。 – Amor