2014-10-08 7 views
8

पर AJAX अनुरोध भेजते समय अनधिकृत मैं अब 2 दिनों के लिए अपने सिर को खरोंच कर रहा हूं। मैं वेबएपीआई संस्करण 2.2 का उपयोग कर रहा हूं और मैं सीओआरएस का उपयोग कर रहा हूं। यह सेटअप सर्वर पक्ष पर काम करता है, मुझे अपने वेब क्लाइंट सर्वर कोड से अधिकृत सामग्री प्राप्त करने की अनुमति है लेकिन मेरे AJAX कॉल में अनधिकृत हो रही है।401 वेब एपीआई

वेब एपीआई कॉन्फ़िग

WebApiConfig:

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 

     // Web API configuration and services 
     // Configure Web API to use only bearer token authentication. 
     config.SuppressDefaultHostAuthentication(); 
     config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); 
     config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ApplicationCookie)); 

     //enable cors 
     config.EnableCors(); 

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     config.Filters.Add(new ValidationActionFilter()); 
    } 
} 

Startup.Auth.cs:

// Configure the db context and user manager to use a single instance per request 
     app.CreatePerOwinContext(UserContext<ApplicationUser>.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 
      { 
       AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
       CookieHttpOnly = true, 
       CookieName = "Outpour.Api.Auth" 
      } 
     ); 

     //app.UseCors(CorsOptions.AllowAll); 
     //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), 
      AllowInsecureHttp = true 
     }; 

     // Enable the application to use bearer tokens to authenticate users 
     app.UseOAuthBearerTokens(OAuthOptions); 

(मैं हर कोशिश की है

यहाँ मेरी विन्यास है ऐप का संयोजन। यूसेर्स (कॉर्सऑप्शन। अलालोअल) ए nd config.EnableCors())

मेरे नियंत्रक विशेषता:

[Authorize] 
[EnableCors("http://localhost:8080", "*", "*", SupportsCredentials = true)] 
[RoutePrefix("api/videos")] 
public class VideosController : ApiController... 

वेब क्लाइंट

अजाक्स कॉल:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) { 
      options.crossDomain = { 
       crossDomain: true 
      }; 
      options.xhrFields = { 
       withCredentials: true 
      }; 
     }); 

     function ajaxGetVideoResolutionList() { 
      var request = { 
       type: "GET", 
       dataType: "json", 
       timeout: Outpour.ajaxTimeOut, 
       url: Outpour.apiRoot + "/videos/resolutions" 
      }; 
      $.ajax(request).done(onAjaxSuccess).fail(onAjaxError); 

कुकी निर्माण:

var result = await WebApiService.Instance.AuthenticateAsync<SignInResult>(model.Email, model.Password); 

      FormsAuthentication.SetAuthCookie(result.AccessToken, model.RememberMe); 

      var claims = new[] 
      { 
       new Claim(ClaimTypes.Name, result.UserName), //Name is the default name claim type, and UserName is the one known also in Web API. 
       new Claim(ClaimTypes.NameIdentifier, result.UserName) //If you want to use User.Identity.GetUserId in Web API, you need a NameIdentifier claim. 
      }; 

      var authTicket = new AuthenticationTicket(new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie), new AuthenticationProperties 
      { 
       ExpiresUtc = result.Expires, 
       IsPersistent = model.RememberMe, 
       IssuedUtc = result.Issued, 
       RedirectUri = redirectUrl 
      }); 

      byte[] userData = DataSerializers.Ticket.Serialize(authTicket); 

      byte[] protectedData = MachineKey.Protect(userData, new[] { "Microsoft.Owin.Security.Cookies.CookieAuthenticationMiddleware", DefaultAuthenticationTypes.ApplicationCookie, "v1" }); 

      string protectedText = TextEncodings.Base64Url.Encode(protectedData); 

      Response.Cookies.Add(new HttpCookie("Outpour.Api.Auth") 
      { 
       HttpOnly = true, 
       Expires = result.Expires.UtcDateTime, 
       Value = protectedText 
      }); 

और अंतिम लेकिन कम से कम नहीं, मेरे शीर्षलेख।

Remote Address:127.0.0.1:8888 
Request URL:http://127.0.0.1/api/videos/resolutions 
Request Method:GET 
Status Code:401 Unauthorized 

**Request Headersview source** 
Accept:application/json, text/javascript, */*; q=0.01 
Accept-Encoding:gzip,deflate,sdch 
Accept-Language:en-US,en;q=0.8 
Cache-Control:no-cache 
Host:127.0.0.1 
Origin:http://localhost:8080 
Pragma:no-cache 
Proxy-Connection:keep-alive 
Referer:http://localhost:8080/video/upload 
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36 

**Response Headersview source** 
Access-Control-Allow-Credentials:true 
Access-Control-Allow-Origin:http://localhost:8080 
Cache-Control:no-cache 
Content-Length:61 
Content-Type:application/json; charset=utf-8 
Date:Wed, 08 Oct 2014 04:01:19 GMT 
Expires:-1 
Pragma:no-cache 
Server:Microsoft-IIS/8.0 
WWW-Authenticate:Bearer 
X-AspNet-Version:4.0.30319 
X-Powered-By:ASP.NET 

डेवलपर टूल और फिडलर का दावा है कि अनुरोध के साथ कोई कुकी नहीं भेजी गई थी।

उत्तर

3

काम करने के लिए मेरा मानना ​​है कि आप कुकीज़ प्रमाणीकरण और वाहक यहां टोकन के बीच मिश्रण कर रहे हैं हो रही है, तो आप अपने अनुरोध के साथ प्राधिकरण शीर्षक में पहुंच टोकन नहीं भेज रहे हैं के बारे में अधिक प्रासंगिक जानकारी मिल सकती है, कि यही कारण है कि आप 401 प्राप्त करते रहते हैं। साथ ही आपको केवल application.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); का उपयोग करके सीओआरएस को अनुमति देने की आवश्यकता है और इसे अपने कंट्रोलर से कॉन्फ़िगरेशन से भी हटा दें।

मेरी Repo here देखें जहां मैंने सीओआरएस लागू किया है और फ्रंट एंड एंगुलरजेएस भी है। यह सही ढंग से काम कर रहा है। इस रेपो के लिए live demo भी है, खुले डेवलपर टूल और अनुरोधों की निगरानी करें, आपको अपने HTTP अनुरोध प्राप्त करने से पहले प्री-फ्लाइट अनुरोध देखना चाहिए।

तुम सिर्फ तब वाहक टोकन का उपयोग कर अपने एपीआई की रक्षा के लिए की जरूरत है मैं सुझाव है कि आप मैं एक ही समस्या है Token Based Authentication पद

+0

को पढ़ने के लिए है, लेकिन मैं संसाधन मेजबान के रूप में WebAPI का उपयोग नहीं कर रही है, लेकिन NancyFX। अगर कर्ल से ऐसा किया जाता है तो सबकुछ मिलता है, लेकिन एंगुलरजेएस ऐप से नहीं। टोकन एंडपॉइंट ठीक है, लेकिन अगर नैन्सी द्वारा प्रदान किए गए मार्ग के लिए जीईटी की बात आती है, तो एएसपी नेट प्रमाणीकरण 401 के साथ एक विकल्प प्रीफलाइट को खारिज कर देता है। मुझे नहीं पता कि इसे कैसे दूर किया जाए। इसके अलावा मुझे यकीन नहीं है कि रेपो डेमो से मेल खाता है या नहीं: रेपो टोकन अनुरोध में client_id का उपयोग करता है, डेमो स्पष्ट रूप से नहीं। संबंधित नहीं, लेकिन एक संकेत, कि दोनों संस्करण अलग हैं। – decades

0

ऐसा इसलिए हो सकता है क्योंकि आपका एपीआई यूआरएल पर आपके कॉलिंग एप्लिकेशन के रूप में नहीं है। एपीआई के लिए आपका URL है: http://127.0.0.1/ (फ़ोल्डर पथ अनदेखी - जो कोई फर्क नहीं पड़ता)

..लेकिन आप http://127.0.0.1:8888 से यह कॉल कर रहे हैं के रूप में बंदरगाह अलग है जो एक अलग साइट के रूप में गिना जाता है। क्योंकि ब्राउज़र सोचता है कि साइट अलग है, यह कुकी नहीं भेजेगी।

क्या आपने एपीआई (उसी पोर्ट के साथ) के समान यूआरएल पर होस्ट किए गए पेज से इसका परीक्षण करने का प्रयास किया है?

सबसे महत्वपूर्ण बात यह है कि आप फिडलर में कुकी को भेजकर देख सकते हैं।

इस on this answer