2017-01-07 1 views
0

WebApi 401 인증되지 않은 문제에 관해 몇 가지 질문과 답변을 보았습니다. 나는 아직도 모든 것이 지역 환경에서 잘 작동하는 이유를 알 수 없다. 그러나 위의 오류는 생산시 발생합니다.WebApi 무단 (401) 제작 중

대부분의 코드 로직을 게시하므로 누군가가 문제의 원인과 해결 방법을 설명 할 수 있습니다. 그리고, 제발, 정확하고 명확하게 노력하십시오. 이 답변을 포함한 모든 답변 : Owin Bearer Token Not Working for WebApi -은 여전히 ​​나에게 불분명합니다.

아래에서 확인할 수 있듯이 제공된 템플릿을 많이 변경하지 않고 사용합니다.

그래서, Global.asax.cs 여기에 일반적인 항목 :

public partial class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     ConfigureAuth(app); 
    } 
} 

그리고 여기 Startup.Auth.cs 파일입니다 : 아래

public class WebApiApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 
     GlobalConfiguration.Configure(WebApiConfig.Register); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 
} 

는 Startup.cs입니다

마지막으로
public partial class Startup 
{ 
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; } 

    public static string PublicClientId { get; private set; } 

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    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(7), 
      // In production mode set AllowInsecureHttp = false 
      AllowInsecureHttp = bool.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_AllowInsecureHttp")) 
     }; 

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

     //****************** GOOGLE AUTHENTICATION ******************************************************* 
     app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() 
     { 
      ClientId = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_Google:ClientID"), 
      ClientSecret = System.Web.Configuration.WebConfigurationManager.AppSettings.Get("Oauth_Google:ClientSecret") 

     }); 
    } 
} 

의 WebApiConfig :

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     // Elmah logging... 
     config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger()); 

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

     // Web API routes 
     config.MapHttpAttributeRoutes(); 

     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
    } 
} 

앞서 언급했듯이 모든 것이 로컬에서 잘 작동합니다. 401 (인증 된) 문제는 원격 서버에 배포 된 경우에만 발생합니다. 우린 우편 배달부와 테스트했는데 운이 없다. 응답 헤더가 표시됩니다. - 서버 → Microsoft-IIS/8.5;

여러분의 도움에 감사드립니다 .... 작동합니다 : - WWW 인증 → 무기명는 NTLM

그래서, 확실히, "무기명 SomeTokenBlablablab 권한 부여"협상.

+1

안녕하세요. 귀하의 webconfig 파일도 게시 할 수 있습니까? ..그리고 또한 . CORS 문제인지 확신 할 수 없습니까? –

답변

0

마지막으로 CORS 구성 (위의 게시물에 포함되지 않은 코드)을 검토 한 후 문제를 해결했습니다!