ASP.NET WEB API 2 OWIN 身份驗證不受支持的 grant_Type
您好我正在嘗試在我的 ASP.NET Web API 2 項目中設置 OAuth 持有者令牌身份驗證。我有兩個項目,一個是 WEB API 項目,另一個是 SPA 項目。
這是我到目前為止所做的:
我創建了 OWIN 啟動類:
[assembly: OwinStartup(typeof(CodeArt.WebApi.App_Start.Startup))] namespace CodeArt.WebApi.App_Start { public class Startup { static Startup() { PublicClientId = "self"; UserManagerFactory = () => new UserManager<UserModel>(new UserStore<UserModel>()); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new OAuthAuthorizatonServer(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<UserModel>> UserManagerFactory { get; set; } public static string PublicClientId { get; private set; } public void Configuration(IAppBuilder app) { ConfigureAuth(app); } public void ConfigureAuth(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalBearer); app.UseOAuthBearerTokens(OAuthOptions); } }我已將 Web API 配置為僅使用不記名令牌身份驗證:
private static void ConfigureBearerTokenAuthentication(HttpConfiguration config) { config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthOptions.AuthenticationType)); }我已配置 WEB API 以支持 CORS:
private static void ConfigureCrossOriginResourseSharing(HttpConfiguration config) { var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); }我已經創建了 OAuthAuthorizationServerProvider 類。從這個類我只設法讓我的程式碼呼叫這個方法:
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { if(context.ClientId == null) { context.Validated(); } return Task.FromResult<object>(null); }它裡面的 if 條件總是被執行。
在我的水療項目中,我有以下內容:
這是我的視圖模型:
var vm = { grant_type: "password", userName: ko.observable(), password: ko.observable() };當登錄按鈕被點擊時,我呼叫這個函式:
var http = { post:function(url, data) { return $.ajax({ url: url, data: data, type: 'POST', contentType: 'application/json', dataType: 'jsonp' }); } } function loginClick() { var model = ko.mapping.toJS(vm.loginModel); var rez = $.param(model); http.post("http://localhost:3439/Token", rez) .done(function (data) { console.log(data); }) .fail(function(eror, stuff, otherstuff) { console.log(eror); console.log(stuff); console.log(otherstuff); }); }我第一次嘗試將文章呼叫 dataType 設置為 json,但出現以下錯誤:
選項 …:3439/令牌 400(錯誤請求)jquery.js:7845
OPTIONS …:3439/Token 請求的資源上不存在“Access-Control-Allow-Origin”標頭。因此,不允許訪問 Origin ‘…:3304’。jquery.js:7845
XMLHttpRequest 無法載入 …3439/Token。請求的資源上不存在“Access-Control-Allow-Origin”標頭。因此,不允許訪問 Origin ‘…3304’。
3 個點代表
http://localhost.第二次我將它的數據類型設置為 jsonp,我得到了一個錯誤,指出不支持“unsupported_grant_type”。
這兩個呼叫都到達了我上面提到的 ValidateClientAuthentication ,但它們都作為失敗的請求被發回。
現在我猜這個問題更多地與我如何發送數據而不是 grand_type 相關,因為 Visual Studion 集合中的 SPA 模板是 grant_type: “password” 的授權類型,就像我做的那樣。
我還讀到我必須序列化數據而不是在 json 中發送它才能在這里工作是發送的確切 json 序列化數據:“grant_type=password&userName=aleczandru&password=happynewYear& moduleId =models%2FappPostModels%2FloginModel”
模型 id 屬性被 Durandal 框架設置為我的 SPA 模板中的所有對象。
誰能告訴我我做錯了什麼我在過去兩天一直試圖解決這個問題?
將以下程式碼行添加到
GrantResourceOwnerCredentials,這會將標頭添加到響應中。context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });有關更多資訊,請參閱: web-api-2-0-cors-and-individual-account-identity
就像 Robin Karlsson 所說,你應該使用:
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);在您的啟動配置中。
並確保它是唯一的 cors 語句(不要混合它們)和 Startup 中的第一個語句。