Angular 2 - 使用 Windows 身份验证使用宁静的 api 调用 [英] Angular 2 - Consuming restful api calls with windows authentication
问题描述
我在使用 Windows 身份验证的远程服务器上的 IIS 7 上托管了一个 .net web api.我想使用 Angular 2 using TypeScript with node 访问 web api.早些时候我收到一个错误对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头'
I have a .net web api hosted on IIS 7 on a remote server which uses windows authentication. I want to access the web api using Angular 2 using TypeScript with node. Earlier i was getting an error 'Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource'
我在托管应用程序的 web.config 中添加了这个
I added this on the hosted Application's web.config
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
但现在我收到未经授权的 401 错误.我已经阅读了有关添加以下代码以允许跨域访问的内容 - 但我不知道在 angular 2 应用程序中的何处添加此代码以及如何编译.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});
这是我尝试使用 get 调用的服务示例代码
Here is the sample code for service that I am trying to make the get call with
@Injectable()
export class TodoService {
todos$: Observable<Todo[]>;
private _baseUrl: string;
private _todosObserver: Observer<Todo[]>;
private _dataStore: {
todos: Todo[]
};
constructor(private _http: Http) {
//let headers: Headers = new Headers();
this._baseUrl = 'http:/SampleServer/Server/api/LoadTodo';
this.todos$ = new Observable(observer => this._todosObserver = observer).share();
this._dataStore = { todos: [] };
}
loadTodos() {
let headers: Headers = new Headers();
//headers.append('Access-Control-Allow-Origin');
headers.append('Authorization', 'Basic ' +
btoa('username:password'));
//let opts: RequestOptions = new RequestOptions();
//opts.headers = headers;
this._http.get(`${this._baseUrl}`,headers).map(response => response.json()).subscribe(data => {
this._dataStore.todos = data;
this._todosObserver.next(this._dataStore.todos);
}, error => console.log('Could not load todos.'));
}
解决此问题的任何帮助都会很棒.
Any help to resolve this issue would be great.
推荐答案
在 ASP.NET Core 解决方案中使用 Angular 2 时,我偶然发现了同样的问题.对我来说,我明确指定了 withCredentials: true
:
I have stumbled upon the same problem when using Angular 2 within an ASP.NET Core solution. For me, I had the explicitly specify withCredentials: true
:
getSomeModels() {
return this.http.get(this.apiBasePath + 'models', { withCredentials: true })
.map(res => res.json());
}
必须在服务器端 (Web API) 启用 CORS,客户端无需其他更改.
CORS must be enabled on the server side (Web API) and no other changes were required on the client side.
注意:用于启用 CORS (Startup.cs) 的服务器端代码
NOTE: Server side code to enable CORS (Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
// injected services
services.AddAuthorization();
services.AddMvc();
//db context
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin(); // For anyone access.
corsBuilder.AllowCredentials();
services.AddCors(options =>
{
options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// middleware configuration
app.UseCors("SiteCorsPolicy");
}
这篇关于Angular 2 - 使用 Windows 身份验证使用宁静的 api 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!