【问题标题】:Windows Authentication In Angular 2 Application and ASP.Net Web APIAngular 2 应用程序和 ASP.Net Web API 中的 Windows 身份验证
【发布时间】:2017-10-27 06:44:32
【问题描述】:

我正在尝试为我的 Angular 4 应用程序实现 Windows 身份验证,该应用程序正在访问 ASP.Net Web API 以满足其所有数据需求。我的 Web API 中有一个名为 AuthenticationController 的控制器,其方法名为 Authenticate,如果身份验证成功,则返回 Domain\Username。 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));
    }
}

当我运行应用程序时,浏览器会要求我输入凭据 - Please See the image 输入凭据后,它会将我带到主页,但 _authenticationHelperService.authenticateUser() 方法不返回用户名。我在控制台上收到如下错误:

XMLHttpRequest 无法加载“MyWebApiURL/api/Authentication/Authenticate”。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin "MyAngularAppUrl"。响应的 HTTP 状态代码为 401。

当我从浏览器(如http://MyWebApiIP:port/api/Authentication/Authenticate)简单地调用 Web API 的 Authenticate 方法时,我成功地获得了我的用户名,但不是来自 Angular 应用程序。

【问题讨论】:

标签: asp.net angular asp.net-web-api windows-authentication angular2-services


【解决方案1】:

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"
    }
  }
}

改成窗口身份验证

【讨论】:

    【解决方案2】:

    除了

    Windows身份验证

    您还需要启用

    匿名认证

    由于 OPTIONS Pre-flight 请求不携带 Auth 头,如果不启用会失败。

    记住要[授权]你所有的控制器。

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 2019-11-30
      • 2012-11-01
      • 1970-01-01
      • 2017-01-23
      • 2016-07-17
      • 2017-07-27
      • 2015-01-03
      • 2017-03-04
      相关资源
      最近更新 更多