当前位置: 首页 > 软件库 > 手机/移动开发 > >

oauth2-oidc-client

Universal OAuth2/OpenID Connect Client library
授权协议 View license
开发语言 JavaScript TypeScript
所属分类 手机/移动开发
软件类型 开源软件
地区 不详
投 递 者 仇正平
操作系统 iOS
开源组织
适用人群 未知
 软件概览

OAUTH2/OIDC Client

Universal OAUTH2/OpenID Connect Client library

Installation:

npm install oauth2-oidc-client --save

Usage

auth.ts (Angular NativeScript)

import { Component, OnInit } from "@angular/core";
import { RouterExtensions, PageRoute } from "nativescript-angular/router";
import * as webViewModule from "tns-core-modules/ui/web-view";
import * as url from "urlparser";
import { AuthService } from "oauth2-oidc-client";
import { timer } from "rxjs/observable/timer";
import { map, filter, switchMap, timeout } from "rxjs/operators";
import "rxjs/add/operator/switchMap";
@Component({
    moduleId: module.id,
    template: // html
    `
    <ActivityIndicator row="1" #activityIndicator [busy]="loading" width="100" height="100" class="activity-indicator"></ActivityIndicator>
    <WebView
        visibility="{{ !loading ? 'visible' : 'collapsed' }}"
        [src]="authURL"
        (loadStarted)="loadStarted($event)"></WebView>
    `
})
export class AuthComponent implements OnInit {
    public authURL;
    public loading: boolean = true;
    public constructor(
        private router: RouterExtensions,
        private pageRoute: PageRoute,
        private authService: AuthService) {
            this.authService.config = {
                authRoute: () => {
                    this.router.navigate([""], { clearHistory: true });
                },
                homeRoute: () => {
                    this.router.navigate(["/home"], { clearHistory: true });
                },
                clientId: "...",
                clientSecret: "...",
                // username: "?...",
                // password: "?...",
                // REDIRECT: "?...",
                // SCOPE: "openid+email+profile", // default
                // state: Math.random().toString(36).substring(7),
                // nonce: "?...",
                oauth2Config: {
                    "issuer": "...",
                    "authorization_endpoint": "...",
                    "token_endpoint": "...",
                    "token_introspection_endpoint": "...",
                    "userinfo_endpoint": "...",
                    "end_session_endpoint": "..."
                }
            };
    }

    // authorization_code login authentication
    public ngOnInit() {
        this.pageRoute.activatedRoute
        .switchMap(activatedRoute => activatedRoute.queryParams)
        .forEach((params) => {
            let action = params["action"];
            if (action == null || action === "login") {
                this.login();
            } else if (action === "logout") {
                this.logout();
            }
            });
    }

    private parseURLData(urlstr) {
        let parsedURL = url.parse(urlstr);
        let code = parsedURL.query ? parsedURL.query.params["code"] : null;
        let state = parsedURL.query ? parsedURL.query.params["state"] : null;
        let nonce = parsedURL.query ? parsedURL.query.params["nonce"] : null;
        let redirectName = parsedURL.path.base;
        if (code && redirectName.match(`\\w*/?${this.authService.config.REDIRECT}`)) {
            return {code, state, nonce};
        } else {
            return null;
        }
    }

    public login() {
        this.authURL = this.authService.login();
        timer(1000).subscribe(x => { this.loading = false; });
    }

    public logout() {
        this.loading = true;
        this.authURL = this.authService.logout();
        timer(1000).subscribe(x => this.login());
    }

    public getUser() {
        this.authService.getUser().subscribe(x => console.log(JSON.stringify(x)));
    }

    public loadStarted(e: webViewModule.LoadEventData) {
        let authData = this.parseURLData(e.url);
        if (authData && authData.state === this.authService.config.state) {
            this.loading = true;
            this.authURL = "";
            this.authService.init(authData.code); //  null for password grant
        }
    }
}

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { NativeScriptFormsModule } from "nativescript-angular/forms";
import { Route } from "@angular/router";

export const routerConfig: Route[] = [
    {
        path: "",
        component: AuthComponent
    }
];
@NgModule({
    schemas: [NO_ERRORS_SCHEMA],
    imports: [
        NativeScriptFormsModule,
        NativeScriptCommonModule,
        NativeScriptRouterModule,
        NativeScriptRouterModule.forChild(routerConfig)
    ],
    declarations: [AuthComponent]
})

export class AuthModule {
    constructor() { }
}

auth.ts (Angular Web)

// beta
declare var document;
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import * as url from "urlparser";
import { AuthService } from "oauth2-oidc-client";
import { timer } from "rxjs/observable/timer";
import "rxjs/add/operator/switchMap";

@Component({
    moduleId: module.id,
    template: // html
    `
    <style>
        .icon-moon {
            font-family: "icomoon";
        }
        @keyframes rotating {
            from {
            transform: rotate(0deg);
            }
            to {
            transform: rotate(360deg);
            }
        }
        .rotating {
            animation: rotating 2s linear infinite;
        }
    </style>
    <Label
        visibility="{{ loading ? 'visible' : 'collapsed' }}"
        class="icon-moon rotating"
        innerText=""
        style="
        font-size: 30;
        display: inline-block;
        position: absolute;
        top:50%;
        left:50%;">
    </Label>
    `
})
export class AuthComponent implements OnInit {
    public authURL;
    public loading: boolean = true;
    public constructor(
        private router: Router,
        private pageRoute: ActivatedRoute,
        private authService: AuthService) {
            this.authService.config = {
                authRoute: () => {
                    this.router.navigate([""], { clearHistory: true });
                },
                homeRoute: () => {
                    this.router.navigate(["/home"], { clearHistory: true });
                },
                clientId: "...",
                clientSecret: "...",
                // username: "?...",
                // password: "?...",
                REDIRECT: window.location.href,
                // SCOPE: "openid+email+profile", // default
                // state: Math.random().toString(36).substring(7),
                // nonce: "?...",
                oauth2Config: {
                    "issuer": "...",
                    "authorization_endpoint": "...",
                    "token_endpoint": "...",
                    "token_introspection_endpoint": "...",
                    "userinfo_endpoint": "...",
                    "end_session_endpoint": "..."
                }
            };
    }

    // authorization_code login authentication
    public ngOnInit() {
        this.pageRoute.activatedRoute
        .switchMap(activatedRoute => activatedRoute.queryParams)
        .forEach((params) => {
            let action = params["action"];
            if (action == null || action === "login") {
                let authData = this.parseURLData(window.location.href);
                if (authData && authData.state === this.authService.config.state) {
                    this.loading = true;
                    this.authURL = "";
                    this.authService.init(authData.code); //  null for password grant
                } else { 
                    this.login();
                }
            } else if (action === "logout") {
                this.logout();
            }
            });
    }

    private parseURLData(urlstr) {
        let parsedURL = url.parse(urlstr);
        let code = parsedURL.query ? parsedURL.query.params["code"] : null;
        let state = parsedURL.query ? parsedURL.query.params["state"] : null;
        let nonce = parsedURL.query ? parsedURL.query.params["nonce"] : null;
        let redirectName = parsedURL.path.base;
        if (code && redirectName.match(`\\w*/?${this.authService.config.REDIRECT}`)) {
            return {code, state, nonce};
        } else {
            return null;
        }
    }

    public login() {
        window.location.href = this.authService.login();
        timer(1000).subscribe(x => { this.loading = false; });
    }

    public logout() {
        this.loading = true;
        window.location.href = this.authService.logout();
        timer(1000).subscribe(x => this.login());
    }

    public getUser() {
        this.authService.getUser().subscribe(x => console.log(JSON.stringify(x)));
    }        
}

import { NgModule, NO_ERRORS_SCHEMA } from "@angular/core";
import { RouterModule } from "@angular/router";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { Route } from "@angular/router";

export const routerConfig: Route[] = [
    {
        path: "",
        component: AuthComponent
    }
];
@NgModule({
    schemas: [NO_ERRORS_SCHEMA],
    imports: [
        FormsModule,
        CommonModule,
        RouterModule,
        RouterModule.forChild(routerConfig)
    ],
    declarations: [AuthComponent]
})

export class AuthModule {
    constructor() { }
}

app.module.ts (Angular)

...
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { AuthService } from "oauth2-oidc-client";

import {
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpInterceptor,
    HttpHeaders
} from "@angular/common/http;
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    constructor(private authService: AuthService) {}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        const token = `Bearer ${this.authService.getToken()}`;
        req = req.clone({
        setHeaders: {
            Authorization: token
        }
        });
        return next.handle(req);
    }
}

@NgModule({
    schemas: [...],
    declarations: [
        ...,
    ],
    bootstrap: [..],
    imports: [
        ...,
    ],
    providers: [
        AuthService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: AuthInterceptor,
            multi: true
        }
    ]
})
export class AppModule { }
...

Auth.js (Web)

// draft
const authService = new (require("oauth2-oidc-client").AuthService)();
authService.config = {...}
authService.init(/*code*/);
var token = authService.getToken();
...........

Notes:

Please setup the Redirect Condition OAuth2/OpenID setting to equal "*" (Any)  

Copyright (C)2018 @medozs Apache-2.0 License

  • 很长一段时间以来,我想使用Spring Security集成一个OpenID Connect提供程序。上次尝试时,我感到它非常复杂,并编写了自己的库。由于Spring Security 5对OAuth2 Client具有本机支持,并且扩展了其对OpenID connect的使用,因此我想了解它的集成有多么容易。 对于此示例,我们将构建一个简单的应用程序,当我们试图访问受保护的端点时,会重定向到go

  • Server RSA Keys: 用于给ID Tokens加密。 django-oidc-provider自带’OIDC_USERINFO’的settings,默认指向一个函数,该函数调用claims(一个字典)和user(user 实例),返回claims(字典),该字典包含所有函数中声明的属性。可以自己定义,并在settings中以点分隔的路径字符串指定该函数。 UserConsent模型可以

  • 一、是什么? OIDC=(Identity, Authentication) + OAuth 2.0。它在OAuth2上构建了一个身份层,是一个基于OAuth2协议的身份认证标准协议。 解决认证问题。 OIDC在OAuth2的access_token的基础上增加了身份认证信息, 通过公钥私钥配合校验获取身份等其他信息—– 即idToken 二、原理 1、术语: EU:End User:一个人类用户

  • http://www.tugberkugurlu.com/archive/simple-oauth-server-implementing-a-simple-oauth-server-with-katana-oauth-authorization-server-components-part-1 https://docs.microsoft.com/en-us/previous-versions/

  • 1. 安装oidc-client ​​​​​​​npm install --save vuex npm install oidc-client 2. 单点登录所需配置项:oidc.js export const identityServerBase = 'http://baidu.com';//目标服务器登录地址 export const vueBase = 'http://localhost:

  • Spring Oauth2-Authorization-Server client_secret_basic 过程 基于 spring-security-oauth2-authorization-server 0.2.3 OAuth2ClientAuthenticationFilter 对 client_id 和 client_secret 进行认证,目前支持四种: JwtClientAssert

 相关资料
  • kong-oidc 是诺基亚开源的一个 Kong 插件,实现了 OpenID Connect Relying Party (RP) 功能。它使用 OpenID Connect Discovery 和基本客户端配置(即授权代码流),针对 OpenID Connect Provider 对用户进行身份验证。 kong-oidc 支持在服务器缓存已解析的 Discovery 文档和验证通过的访问令牌(A

  • 我试图弄清楚我需要做什么来实现SSO。所以基本上我正在构建: a)php网站(example.com) b)android app(com.android.example) 网站和应用程序将有一个登录表单社交登录按钮,通过twitter、FB等进行身份验证。 我不明白的是,人们如何在站点上实现登录表单,在没有重定向的情况下对OIDC服务器进行身份验证?如果我理解正确-OIDC流要求将用户重定向到不

  • Angular Lib for OpenID Connect & OAuth2 Secure your Angular app using the latest standards for OpenID Connect & OAuth2. Provides support for token refresh, all modern OIDC Identity Providers and more.

  • 我正在使用Quarkus 1.0.1框架开发一套微服务。我希望使用KeyCloak8.0.1作为我的身份提供程序来保护这些信息。我已经在一个Docker容器中启动并运行了Keycloak,并为我的微服务配置了一个领域和相应的客户机。现在我到了我想保护他们的地步,我遇到了一个问题。 我的REST服务没有为它配置的注释或任何授权要求。这应该意味着,即使我没有经过身份验证,我也能够访问该服务。但是,当我

  • 目前我正在开发Angular2应用程序,希望使用B2C租户进行身份验证。它不起作用,因为我遇到了一个错误: 发现文档中应包含无效的颁发者: 设置和配置与https://github.com/manfredsteyer/angular-oauth2-oidc描述的一样精确。 在给定的示例中,使用了以下函数: 不幸的是,loadDiscoveryDocumentAndTryLogin对我不起作用,因为

  • 我已经按照Grafana文档,我不知道如何配置Grafana与OpenID连接。https://grafana.com/docs/grafana/latest/auth/generic-oauth/ 我们已经用OpenID connect配置了几个应用程序,这些应用程序运行正常。 我需要的是配置OpenID连接到Grafana。 我们所拥有的: 客户端ID 客户端密码 公开揭露Grafana 此外