Angular 2 使用 ASP.NET 身份令牌登录

Posted

技术标签:

【中文标题】Angular 2 使用 ASP.NET 身份令牌登录【英文标题】:Angular 2 Login using ASP.NET Identity Token 【发布时间】:2017-02-20 01:20:10 【问题描述】:

我正在开发一个对 ASP.NET Web API 2 服务进行服务调用的 Angular 2 应用程序。在此服务中,已在 WebApiConfig 中启用了 CORS,如下所示:

public static class WebApiConfig

    public static void Register(HttpConfiguration config)
    
        ...

        var cors = new EnableCorsAttribute("*", "*", "*");

        config.EnableCors(cors);

        ...

    

这一直运行良好,我在使用 CORS 时没有遇到任何问题。例如调用/api/users成功检索所有用户。

但是,现在我正在尝试将 .NET 身份令牌用于登录功能,这给我带来了与 CORS 相关的问题。当调用/token 在我的login.service.ts 中执行登录时:

loginUser(username: string, password: string) 
    let serviceURL = 'http://myurl/token';

    let body = 'username=' + username + '&password=' + password + '&grant_type=password';

    let headers: Headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');

    let options: RequestOptions = new RequestOptions(
        headers: headers
    );

    return this.http.post(serviceURL, body, options)
        .map(res => this.extractData(res))
        .catch(this.handleError);

我收到以下错误:

XMLHttpRequest cannot load http://myurl/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.

我发现这令人困惑有两个原因:

    如上所述,我在任何 /api 调用中都没有遇到 CORS 问题 当我输入正确的凭据时,调用“成功”(即Status Code 200,但我收到上面列出的错误。

我查看了许多具有类似实现的不同文章,但我似乎找不到我的问题所在。

【问题讨论】:

【参考方案1】:

好的,我终于找到了发生这种情况的原因。正如here 中强调的那样,/token 端点似乎是在 WebApiConfig 之前初始化的,因此此处的任何设置都不会为 /token 端点启用 CORS。

要为此端点启用它,应在 IdentityConfig.cs Create 函数中添加以下内容:

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)


    context.Response.Headers.Add("Access-Control-Allow-Origin", new[]  "*" );

    ...


【讨论】:

以上是关于Angular 2 使用 ASP.NET 身份令牌登录的主要内容,如果未能解决你的问题,请参考以下文章

Angular 和 Asp.Net Core - 启用 2 因素身份验证

ASP.NET Core 中的 Jwt 令牌身份验证

控制器 ASP.net 核心 2.1 中的 Jwt 角色身份验证

Azure AD for Angular + ASP.net web api - Msal Angular HTTP 拦截器不为 POST 方法附加令牌

ASP.NET Core 2.1 API JWT 令牌 Session.id 在每次请求时都会更改

处理 OAuth 2.0 身份验证 - 在 ASP.NET MVC 应用程序中获取令牌重定向令牌响应