Angular 2 应用程序和 ASP.Net Web API 中的 Windows 身份验证

4
我正在尝试为我的Angular 4应用程序实现Windows身份验证,该应用程序访问ASP.Net Web API以满足其所有数据需求。 我在我的Web API中有一个名为AuthenticationController的控制器,其中包含一个名为Authenticate的方法,如果身份验证成功,则返回域\用户名。 AuthenticationController的代码如下:
namespace MyAppWebAPI.Controllers
{
    [Authorize]
    public class AuthenticationController : ApiController
    {
        [HttpGet]
        public LoginModels Authenticate()
        {
            Debug.Write($"AuthenticationType: {User.Identity.AuthenticationType}");
            Debug.Write($"IsAuthenticated: {User.Identity.IsAuthenticated}");
            Debug.Write($"Name: {User.Identity.Name}");

            if (User.Identity.IsAuthenticated)
            {
                //return Ok($"Authenticated: {User.Identity.Name}");
                return new LoginModels { DomainName = User.Identity.Name, Role = "Admin" };
            }
            else
            {
                throw new Exception ("Not authenticated");
            }
        }
    }
}

其中LoginModels是以下模型:

public class LoginModels
{
    public string DomainName { get; set; }
    public string Role { get; set; }
}

我已经在AppStart文件夹下的WebApiConfig.cs中启用了CORS,其代码如下:

namespace MyAppWebAPI
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

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

            //Resolve CORS Issue
            var cors = new EnableCorsAttribute("http://MyAngularApplicationIP:port", "*", "*") { SupportsCredentials = true };
            config.EnableCors(cors);
        }
    }
}

此外,我已经在我的Web.config中启用了Windows身份验证:
<authentication mode="Windows"/>
    <authorization>
        <deny users="?" />
    </authorization>
</system.web>

现在在我的Angular应用程序中,我有一个名为AuthenticationHelperService的服务,如下所示:
@Injectable()
export class AuthenticationHelperService {

    constructor(
        private _httpHelperService: HttpHelperService,
        private _http: Http,
        private _requestOptions: RequestOptions,
    ) { }

    public authenticateUser(): Observable<any> {
        console.log('Calling GetUser');
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers, withCredentials: true });
        return this._http
            .get('WebApiURL:port/api/Authentication/Authenticate', options)
            .map(this._httpHelperService.extractData)
            .catch(this._httpHelperService.handleError);
    }
}

请注意,我已经在请求选项中启用了withCredentials: true。此外,这里的_httpHelperService.extractData只是将我的响应转换为JSON格式,_httpHelperService.handleError会在控制台上记录错误(如果有的话)。
现在,我正在从组件中调用此服务方法,在ngOnInit方法中加载页面时如下:
export class MasterComponent implements OnInit {

    constructor(
        private _userLoginService : UserLoginService,
        private _authenticationHelperService: AuthenticationHelperService
    ) { }

    private userName: any;

    ngOnInit() {
        this._authenticationHelperService.authenticateUser().subscribe(
            data => this.userName = data,
            error => console.log('Authentication Error :: ' + error),
            () => console.log('Current User :: ' + this.userName));
    }
}

当我运行应用程序时,浏览器要求我输入凭据-请参见图像 输入凭据后,它会带我到主页,但_authenticationHelperService.authenticateUser()方法不返回用户名。我在控制台上得到以下错误: XMLHttpRequest无法加载"MyWebApiURL/api/Authentication/Authenticate"。预检请求的响应未通过访问控制检查:所请求的资源上不存在'Access-Control-Allow-Origin'标头。因此,源“ MyAngularAppUrl”不允许访问。响应具有HTTP状态代码401。 当我仅从浏览器调用Web API的Authenticate方法,如http://MyWebApiIP:port/api/Authentication/Authenticate时,我可以成功获取我的用户名,但无法从Angular应用程序中获取。

CORS预检请求不起作用,应该返回HTTP 200,但实际上收到了401。请查看此示例,了解如何在您的Web API中配置CORS:https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api - andresm53
6
你解决了这个问题吗?如果是的话,解决方法是什么? - Ben Cameron
1
@BenCameron 我按照这个教程操作:https://spikesapps.wordpress.com/2016/09/08/how-to-implement-windows-authentication-in-an-angularjs-application-with-a-stand-alone-web-api/,一切都很顺利。 - Reed
2个回答

1
除了Windows身份验证外,您还需要启用匿名身份验证,因为OPTIONS Pre-flight请求不携带Auth标头,如果未启用则会失败。只需记住对所有控制器进行[Authorize]即可。

0

launchSettings.json

你可以在项目的属性文件夹中找到这个文件。

{
  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:53072/",
      "sslPort": 0
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "AdvantureWeb": {
      "commandName": "Project"
    }
  }
}

改为Windows身份验证


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接