启用WebAPI CORS进行Angular 2身份验证 [英] Enabling WebAPI CORS for Angular 2 authentification

查看:68
本文介绍了启用WebAPI CORS进行Angular 2身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在stackoverflow上看到了一些答案,但我迷路了.

I've seen a few answers on stackoverflow and I'm lost.

我有webapi 2 +独立的angular 2 webapi项目来自模板.我唯一改变的是我添加了CORS 并转到IdentityConfig.cs> ApplicationUserManager Create()

I have webapi 2 + standalone angular 2 webapi project is from template. the only thing i've changed is that i added CORS and following line to IdentityConfig.cs > ApplicationUserManager Create()

context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "http://localhost:3000" });

这里我具有模板的所有标准:

here I've all standard from template:

[Authorize]
public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
            return new string[] { "value1", "value2" };
    }

在客户端,我具有获取访问令牌的功能,该功能可以正常工作:

On the client side I have function to get access token, that works properly:

authenticate(loginInfo: Login): boolean {

        let headers = new Headers(); 
        headers.append('Content-Type', 'application/x-www-form-urlencoded');
        this.http.post(this.baseUrl + 'Token', 'grant_type=password&username=alice2@example.com&password=Password2!',
            {
                headers: headers
            })
            .subscribe(
                data => this.saveAuthToken(<AccessToken>(data.json())),
                err => this.handleError(err),
                () => console.log('authentication Complete')
        );           

        return true;        
    }

获取功能,无需身份验证即可正常运行(带注释的代码):

And get function, that works ok without authentication (commented code) :

get(url: string) {         

    var jwt = sessionStorage.getItem(this.idTokenName);
    var authHeader = new Headers();       
    if (jwt) {
        authHeader.append('Authorization', 'Bearer ' + jwt);
    }        

    return this.http.get(this.apiUrl + url, {
            headers: authHeader
        })
        .map(res => res.json())
        .catch(this.handleError);       

    //return this.http.get(this.apiUrl + url)
    //    .map(res => res.json())
    //    .catch(this.handleError);   
}  

但是当我尝试添加Authorization标头服务器时返回:

But when i try to add Authorization header server returns:

XMLHttpRequest cannot load http://localhost:3868/api/values. Response for preflight has invalid HTTP status code 405

如何允许用户正确通过Angular进行身份验证?

How to allow user to authenticate through Angular properly?

推荐答案

  1. 安装软件包Microsoft.Owin.Cors
  2. 添加到App_Start> Startup.Auth.cs> ConfigureAuth(IAppBuilder应用)

  1. Install-Package Microsoft.Owin.Cors
  2. Add to App_Start > Startup.Auth.cs > ConfigureAuth(IAppBuilder app)

   app.UseCors(CorsOptions.AllowAll);

仅一行.就是这样.

这篇关于启用WebAPI CORS进行Angular 2身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆