首页 > 解决方案 > Angular 6、节点、护照和 OAuth2

问题描述

我想允许我的 angular-cli v6 应用程序的用户使用 github 凭据登录。我正在使用护照和护照-github。

节点服务器中的关键部分是这个

    passport.use(
        new Strategy(
            {
                clientID: '<clientID>',
                clientSecret: '<ClientSecret>',
                callbackURL: 'http://myapp/authenticated'
            },
            (accessToken, refreshToken, profile, cb) => {
                return cb(null, profile);
            }
        )
    );

    this.config.app.get(
        '/login',
        passport.authenticate('github', {
            scope: [
                'user',
                'notifications',
                'gist',
                'repo',
                'admin:org',
                'admin:public_key',
                'admin:repo_hook',
                'admin:org_hook'
            ]
        })
    );

    this.config.app.get(
        '/authenticated',
        passport.authenticate('github', {
            successRedirect: '/home',
            failureRedirect: '/signin',

            session: false
        }),
        (req, res) => {
            res.redirect('/home');
        }
    );
}

所以我启动了 ng-serve 并获取了我的登录表单(在 /signin 上)。当我按下获取按钮时,代码会执行此操作

public async login(username: string, password: string) {
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        })
    };

    const result = await this.http
        .get<any>('/login', httpOptions)
        .toPromise();

此时,我收到网络和控制台错误

404 https://github.com/login/oauth/authorize?response_type=code&redirect....

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://myapp' is therefore not allowed access.

但是,如果我将角度代码更改为读取

public async login(username: string, password: string) {
    window.open('/login', '_self');

然后应用程序被授权到 github,并且用户重定向到主页

当直接从浏览器地址栏输入的相同 url 工作正常时,我做错了什么会产生 404 和 cors 错误的角度 http 客户端?

更新#1:我注意到对https://github.com/login/oauth/authorize的请求window.open('/login'是一个GET,但是角度 http 客户端是一个可以解释 404的OPTIONS

更新#2:如果我httpOptions从请求中删除,404 消失......但不是控制台中的 CORS 错误

公共异步登录(用户名:字符串,密码:字符串){

const result = await this.http
    .get<any>('/login')
    .toPromise();

更新#3:如果我href="'/login'"在按钮 html 中有登录,那么登录就可以了,没有 cors 错误。所以我想我现在已经达到了如何href在角度方法中模拟调用的地步

标签: angularcorspassport.js

解决方案


您无法模拟 href 调用,也无法在“幕后”XHR 请求中进行登录。要进行这种登录,您必须实际将用户发送到该站点。

如果您需要以编程方式执行此操作,请执行以下操作:

window.location.href = ...


推荐阅读