oauth2-oidc-client Universal OAuth2/OpenID Connect

我要开发同款
匿名用户2021年11月26日
44阅读
开发技术JavaScriptTypeScript
所属分类手机/移动开发
授权协议View license

作品详情

OAUTH2/OIDCClient

UniversalOAUTH2/OpenIDConnectClientlibrary

Installation:

npminstalloauth2-oidc-client--save

Usageauth.ts(AngularNativeScript)import{Component,OnInit}from"@angular/core";import{RouterExtensions,PageRoute}from"nativescript-angular/router";import*aswebViewModulefrom"tns-core-modules/ui/web-view";import*asurlfrom"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`<ActivityIndicatorrow="1"#activityIndicator[busy]="loading"width="100"height="100"class="activity-indicator"></ActivityIndicator><WebViewvisibility="{{!loading?'visible':'collapsed'}}"[src]="authURL"(loadStarted)="loadStarted($event)"></WebView>`})exportclassAuthComponentimplementsOnInit{publicauthURL;publicloading:boolean=true;publicconstructor(privaterouter:RouterExtensions,privatepageRoute:PageRoute,privateauthService: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_codeloginauthenticationpublicngOnInit(){this.pageRoute.activatedRoute.switchMap(activatedRoute=>activatedRoute.queryParams).forEach((params)=>{letaction=params["action"];if(action==null||action==="login"){this.login();}elseif(action==="logout"){this.logout();}});}privateparseURLData(urlstr){letparsedURL=url.parse(urlstr);letcode=parsedURL.query?parsedURL.query.params["code"]:null;letstate=parsedURL.query?parsedURL.query.params["state"]:null;letnonce=parsedURL.query?parsedURL.query.params["nonce"]:null;letredirectName=parsedURL.path.base;if(code&&redirectName.match(`\\w*/?${this.authService.config.REDIRECT}`)){return{code,state,nonce};}else{returnnull;}}publiclogin(){this.authURL=this.authService.login();timer(1000).subscribe(x=>{this.loading=false;});}publiclogout(){this.loading=true;this.authURL=this.authService.logout();timer(1000).subscribe(x=>this.login());}publicgetUser(){this.authService.getUser().subscribe(x=>console.log(JSON.stringify(x)));}publicloadStarted(e:webViewModule.LoadEventData){letauthData=this.parseURLData(e.url);if(authData&&authData.state===this.authService.config.state){this.loading=true;this.authURL="";this.authService.init(authData.code);//nullforpasswordgrant}}}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";exportconstrouterConfig:Route[]=[{path:"",component:AuthComponent}];@NgModule({schemas:[NO_ERRORS_SCHEMA],imports:[NativeScriptFormsModule,NativeScriptCommonModule,NativeScriptRouterModule,NativeScriptRouterModule.forChild(routerConfig)],declarations:[AuthComponent]})exportclassAuthModule{constructor(){}}auth.ts(AngularWeb)//betadeclarevardocument;import{Component,OnInit}from"@angular/core";import{Router}from"@angular/router";import*asurlfrom"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";}@keyframesrotating{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}.rotating{animation:rotating2slinearinfinite;}</style><Labelvisibility="{{loading?'visible':'collapsed'}}"class="icon-moonrotating"innerText=""style="font-size:30;display:inline-block;position:absolute;top:50%;left:50%;"></Label>`})exportclassAuthComponentimplementsOnInit{publicauthURL;publicloading:boolean=true;publicconstructor(privaterouter:Router,privatepageRoute:ActivatedRoute,privateauthService: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_codeloginauthenticationpublicngOnInit(){this.pageRoute.activatedRoute.switchMap(activatedRoute=>activatedRoute.queryParams).forEach((params)=>{letaction=params["action"];if(action==null||action==="login"){letauthData=this.parseURLData(window.location.href);if(authData&&authData.state===this.authService.config.state){this.loading=true;this.authURL="";this.authService.init(authData.code);//nullforpasswordgrant}else{this.login();}}elseif(action==="logout"){this.logout();}});}privateparseURLData(urlstr){letparsedURL=url.parse(urlstr);letcode=parsedURL.query?parsedURL.query.params["code"]:null;letstate=parsedURL.query?parsedURL.query.params["state"]:null;letnonce=parsedURL.query?parsedURL.query.params["nonce"]:null;letredirectName=parsedURL.path.base;if(code&&redirectName.match(`\\w*/?${this.authService.config.REDIRECT}`)){return{code,state,nonce};}else{returnnull;}}publiclogin(){window.location.href=this.authService.login();timer(1000).subscribe(x=>{this.loading=false;});}publiclogout(){this.loading=true;window.location.href=this.authService.logout();timer(1000).subscribe(x=>this.login());}publicgetUser(){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";exportconstrouterConfig:Route[]=[{path:"",component:AuthComponent}];@NgModule({schemas:[NO_ERRORS_SCHEMA],imports:[FormsModule,CommonModule,RouterModule,RouterModule.forChild(routerConfig)],declarations:[AuthComponent]})exportclassAuthModule{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()exportclassAuthInterceptorimplementsHttpInterceptor{constructor(privateauthService:AuthService){}intercept(req:HttpRequest<any>,next:HttpHandler):Observable<HttpEvent<any>>{consttoken=`Bearer${this.authService.getToken()}`;req=req.clone({setHeaders:{Authorization:token}});returnnext.handle(req);}}@NgModule({schemas:[...],declarations:[...,],bootstrap:[..],imports:[...,],providers:[AuthService,{provide:HTTP_INTERCEPTORS,useClass:AuthInterceptor,multi:true}]})exportclassAppModule{}...Auth.js(Web)//draftconstauthService=new(require("oauth2-oidc-client").AuthService)();authService.config={...}authService.init(/*code*/);vartoken=authService.getToken();...........Notes:PleasesetuptheRedirectConditionOAuth2/OpenIDsettingtoequal"*"(Any)

Copyright(C)2018@medozsApache-2.0License

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论