我正在尝试为我的 Angular 4 应用程序实现 Windows 身份验证,该应用程序正在访问 ASP.Net Web API 以满足其所有数据需求。我的 Web API 中有一个名为 AuthenticationController
的 Controller ,它有一个名为 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 cannot load "MyWebApiURL/api/Authentication/Authenticate". Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin "MyAngularAppUrl" is therefore not allowed access. The response had HTTP status code 401.
当我简单地从浏览器调用 Web API 的 Authenticate 方法时,比如 http://MyWebApiIP:port/api/Authentication/Authenticate
然后我成功获得了我的用户名,但不是来自 Angular 应用程序.
最佳答案
除了
Windows 身份验证
你还需要启用
匿名身份验证
因为 OPTIONS Pre-flight 请求不携带 Auth header ,如果未启用将失败。
只记得[授权]你所有的 Controller 。
关于asp.net - Angular 2 应用程序和 ASP.Net Web API 中的 Windows 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44200444/