我正在尝试为我的Angular 4应用程序实现Windows身份验证,该应用程序访问ASP.Net Web API以满足其所有数据需求。 我在我的Web API中有一个名为
此外,我已经在我的
现在在我的Angular应用程序中,我有一个名为
请注意,我已经在请求选项中启用了
现在,我正在从组件中调用此服务方法,在
当我运行应用程序时,浏览器要求我输入凭据-请参见图像 输入凭据后,它会带我到主页,但
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应用程序中获取。