【发布时间】: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 应用程序。
【问题讨论】:
-
CORS 预检请求不起作用,它应该返回 HTTP 200,而是接收 401,看看此示例是否有助于了解如何在 Web API docs.microsoft.com/en-us/aspnet/web-api/overview/security/…中配置 CORS@
-
您设法解决了这个问题吗?如果是这样,解决方案是什么?
-
@BenCameron 我按照本教程进行操作:spikesapps.wordpress.com/2016/09/08/…,一切正常。
标签: asp.net angular asp.net-web-api windows-authentication angular2-services