如何防止Windows身份验证将浏览器重定向到API URL?

时间:2018-05-02 14:57:29

标签: angular iis asp.net-core windows-authentication

我们有一个Angular4前端,它使用Windows身份验证调用IIS中托管的ASP.NET Core 2.0 Web API。首次加载前端或隐身时,需要登录,但成功登录后不会重定向回前端。它的表现如下:

  • 导航至http://localhost:4200
  • 的前端
  • 登录提示会在http://localhost:53465
  • 处弹出API网址
  • 成功登录后,浏览器会停留在http://localhost:53465,而不是重定向到http://localhost:4200

最近这一切都开始发生在Chrome的最新更新中,之前这绝不是一个问题;登录后,您将被重定向到前端,无论您打算导航到哪个页面。

以下是前端站点上web.config的内容:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Angular" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
          </conditions>
          <action type="Rewrite" url="/" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

以下是API网站的web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="autoFormsAuthentication" value="false" />
    <add key="enableSimpleMembership" value="false" />
    <add key="PreserveLoginUrl" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="Windows" />
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="aspNetCore" />
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
    </handlers>
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" startupTimeLimit="3600" requestTimeout="23:00:00" forwardWindowsAuthToken="true" />
    <security>
      <authorization>
        <remove users="*" roles="" verbs="" />
        <add accessType="Allow" users="?" verbs="OPTIONS" />
        <add accessType="Allow" roles="USERS" />
      </authorization>
    </security>
  </system.webServer>
</configuration>

以下是我们如何在Angular中发出http请求:

getPendingRequests(owner: string): Observable<any[]> {
        let url = `${this.baseUrl}pending`;
        return this._http.get(url).map((res: Response) => res.json());
    }

以及随之发送的选项:

@Injectable()
export class NoCacheRequestOptions extends BaseRequestOptions {
    constructor () {
        super();
        this.headers.append('Cache-Control','no-cache');
        this.headers.append('Pragma', 'no-cache');
        this.headers.append('Expires', 'Sat, 01 Jan 2000 00:00:00 GMT');
        this.headers.append('Content-Type', 'application/json');
        this.withCredentials = true;
      }
}

以下是API端点示例:

[Route("pending")]
[Authorize]
public class PendingCorrespondenceController : Controller
{
    ....
    public async Task<IActionResult> GetPendingCorrespondence()
        {

我们用于API的Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(Configuration);
            services.AddMemoryCache();
            services.AddMvc();
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddAuthentication("CookieAuthenticationScheme")
                .AddCookie("CookieAuthenticationScheme");
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin", builder =>
                {
                    builder.WithOrigins(Configuration["CORS:AllowedOrigins"]);
                    builder.AllowCredentials();
                    builder.AllowAnyHeader();
                    builder.AllowAnyMethod();
                });
            });

            services.AddSingleton<IDashboardData, CacheDashboardData>();
            services.AddSingleton<ICorrespondencePermission, CorrespondencePermission>();
            services.AddSingleton<IPendingCorrespondence, PendingCorrespondence.PendingCorrespondence>();
            services.AddSingleton<IHoldForReview, HoldForReview.HoldForReview>();
            services.AddSingleton<IActiveDirectory, ActiveDirectory>();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment()) app.UseDeveloperExceptionPage();
            app.UseAuthentication();
            app.UseCors("AllowSpecificOrigin");
            app.UseMiddleware<PermissionsMiddleware>();
            app.UseMiddleware<GlobalExceptionLogger>();
            app.UseMvc().UseMvcWithDefaultRoute();
        }

我们一直在努力解决这个问题几天没有运气,有什么东西显而易见我们缺席了吗?

0 个答案:

没有答案