【发布时间】:2016-05-25 15:50:11
【问题描述】:
我有一个为 CORS 配置的 Web API 项目,并在其中一个 APIController 上实现 [Authorize]。当我删除 [Authorize] 时,我可以从 WPF 客户端访问 API,但是当它到位时,调用似乎丢失了。这是我为请求令牌而设置的。
在WPF代码后面
internal void RefreshRecentFilesList()
{
//Get the token
var token = GetAPIToken(email, password, "http://localhost:50006").Result;
MessageBox.Show(token);
}
private static async Task<string> GetAPIToken(string userName, string password, string apiBaseUri)
{
using (var client = new HttpClient())
{
//setup client
client.BaseAddress = new Uri(apiBaseUri);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token.AccessToken);
//setup login data
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("grant_type", "password"),
new KeyValuePair<string, string>("username", userName),
new KeyValuePair<string, string>("password", password),
});
//send request
HttpResponseMessage responseMessage = await client.PostAsync("/Token", formContent);
//get access token from response body
var responseJson = await responseMessage.Content.ReadAsStringAsync();
var jObject = JObject.Parse(responseJson);
return jObject.GetValue("access_token").ToString();
}
}
在 Web API 项目中 WebAPIConfig.cs
//Enable CORS
var cors = new EnableCorsAttribute("*", "*", "GET");
config.EnableCors(cors);
在 API 控制器中
[HttpGet]
//[Authorize]
public List<FileInfo> GetFileTypes()
{
List<FileInfo> fileInfos = new List<FileInfo>();
...
在 StartAuth.cs 中
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
// 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);
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
// Enable the application to use bearer tokens to authenticate users
app.UseOAuthBearerTokens(OAuthOptions);
当我运行 WPF 并逐步执行代码时,它会到达发送请求行,然后就挂起。
谁能指点我正确的方向?
非常感谢
【问题讨论】:
标签: c# wpf asp.net-web-api