Angular 2的WebApi Owin身份验证仅适用于本地主机

时间:2018-10-18 13:33:45

标签: angular asp.net-web-api owin restful-authentication owin-middleware

我有针对OWIN承载令牌认证的实现,该认证在本地主机上可以完美运行。 (本地)。 但是当我在iis上托管该应用程序时,Authorize方法不会填充access_token并将其附加到url(就像在本地一样)。

你有什么想法吗? 我的代码是:

WebApiConfig

private E findHelp(BinaryNode<Key, E> rt, Key k) {
        int compare = k.compareTo(rt.getKey()); 
        if (compare==0) {
            System.out.println(rt.getValue()); // I'm getting C2-112 here 
            return rt.getValue(); // so I expect a return of C2-112
        } else if (compare >0 ) {
            if (rt.getRight() == null) {
                return null;
            } else {
                findHelp(rt.getRight(), k);
            }
        } else {
            if (rt.getLeft() == null) {
                return null;
            } else {
                findHelp(rt.getLeft(), k);
            }
        }
        return null;
    } // 

public E find(Key k) {
        E tmp = findHelp(root, k); 
        System.out.println(tmp); // this prints null, not C2-112
        return findHelp(root, k); // and so I return null
    }

Startup.Auth

// Web API routes
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
        // Use camel case for JSON data.
        //config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        // Make Newtonsoft.Json default json serializer
        var formatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
        if (formatter != null)
        {
            formatter.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
        }

Angular authentication.service:

// Enable the application to use OAuthAuthorization. You can then secure your Web APIs
    static Startup()
    {
        PublicClientId = "web";

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            AuthorizeEndpointPath = new PathString("/Account/Authorize"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true,
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    private static void ApplyRedirect(CookieApplyRedirectContext context)
    {
        Uri absoluteUri;
        if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri))
        {
            var path = PathString.FromUriComponent(absoluteUri);
            if (path == context.OwinContext.Request.PathBase + context.Options.LoginPath)
            {
                #if DEBUG
                    context.RedirectUri = "http://localhost:34000/authentication/login";
                #else
                    context.RedirectUri = "https://sigma.cmtrading.com/authentication/login";
                #endif
            }
        }

        context.Response.Redirect(context.RedirectUri);
    }

    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(DbLoader.GetDb);
        app.CreatePerOwinContext<SigmaUserManager>(SigmaUserManager.Create);
        app.CreatePerOwinContext<SigmaSignInManager>(SigmaSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Authentication/Login"),
            LogoutPath = new PathString("/Authentication/Logout"),
            Provider = new CookieAuthenticationProvider
            {
                // Applying redirect to api domain
                OnApplyRedirect = ApplyRedirect,

                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<SigmaUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(20),
                regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

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

0 个答案:

没有答案