Angular_03_oidc

oidc-client

https://github.com/IdentityModel/oidc-client-js
npm install oidc-client --save

配置

  • environment
openIdConnectSettings: {
    authority: 'https://localhost:6001/',
    client_id: 'blog-client',
    redirect_uri: 'http://localhost:4200/signin-oidc',
    scope: 'openid profile email restapi',
    response_type: 'id_token token',
    post_logout_redirect_uri: 'http://localhost:4200/',
    automaticSilentRenew: true,
    silent_redirect_uri: 'http://localhost:4200/redirect-silentrenew'
  }
  • 后端config
 // SPA client using implicit flow +++++>>>>Angular
                new Client
                {
                    ClientId = "blog-client",
                    ClientName = "Blog Client",
                    ClientUri = "http://localhost:4200",

                    AllowedGrantTypes = GrantTypes.Implicit,
                    AllowAccessTokensViaBrowser = true,
                    RequireConsent = false, //是否需要點(diǎn)擊同意 
                    AccessTokenLifetime=180, //有效期180s

                    RedirectUris =
                    {
                       "http://localhost:4200/signin-oidc",
                       "http://localhost:4200/redirect-silentrenew",
                    },

                    PostLogoutRedirectUris = { "http://localhost:4200/" },
                    AllowedCorsOrigins = { "http://localhost:4200" },

                    AllowedScopes = {
                     IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "restapi"
                    }
                }
  • 后端startup配置跨域
 //配置跨域        
            services.AddCors(options =>
            {
                options.AddPolicy("AngularClient", policy =>
                 {
                     policy.WithOrigins("http://localhost:4200")
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                 });
            });
 app.UseCors();
  • Angular創(chuàng)建service
export class OpenIdConnectService {

  private userManager: UserManager = new UserManager(environment.openIdConnectSetting);

  private currentUser: User;

  userLoaded$ = new ReplaySubject<boolean>(1);  // observerable rxjs

  get userAvailable(): boolean {
    return this.currentUser != null;
  }

  get user(): User {
    return this.currentUser;
  }

  constructor() {
    this.userManager.clearStaleState();

    this.userManager.events.addUserLoaded(user => {
      if (!environment.production) {
        console.log('User loaded.', user);
      }
      this.currentUser = user;
      this.userLoaded$.next(true); // 廣播
    });

    this.userManager.events.addUserUnloaded((e) => {
      if (!environment.production) {
        console.log('User unloaded.');
      }
      this.currentUser = null;
      this.userLoaded$.next(false);
    });
  }

  triggerSignIn() {
    this.userManager.signinRedirect().then(() => {
      if (!environment.production) {
        console.log('Redirction to signin triggered');
      }
    });
  }

  handleCallback() {
    this.userManager.signinRedirectCallback().then(user => {
      if (!environment.production) {
        console.log('callback after signin handled.', user);
      }
    });
  }

  handleSilentCallback() {
    this.userManager.signinSilentCallback().then(user => {
      this.currentUser = user;
      if (!environment.production) {
        console.log('callback after silent signin handled.', user);
      }
    });
  }

  triggerSignOut() {
    this.userManager.signoutRedirect().then(resp => {
      if (!environment.production) {
        console.log('redirection to sign out triggered', resp);
      }
    });
  }
}
  • signin-oidc component
export class SigninOidcComponent implements OnInit {

  constructor(private openIdConnectService: OpenIdConnectService,
    private router: Router) { }

  ngOnInit() {
    this.openIdConnectService.userLoaded$.subscribe((userLoaded) => {
      if (userLoaded) {
        this.router.navigate(['./']);
      } else {
        if (!environment.production) {
          console.log('An error happened: user wasn\'t loaded.');
        }
      }
    });

    this.openIdConnectService.handleCallback();
  }

  • redirect-silent-renew component
export class RedirectSilentRenewComponent implements OnInit {

  constructor(private openIdConnectService: OpenIdConnectService) { }

  ngOnInit() {
    this.openIdConnectService.handleSilentCallback();
  }

}
  • RequireAuthenticatedUserRoute Guard
export class RequireAuthenticatedUserRouteGuard implements CanActivate {

  constructor(
    private openIdConnectService: OpenIdConnectService,
    private router: Router
  ) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (this.openIdConnectService.userAvailable) {
      return true;
    } else {
      // trigger signin
      this.openIdConnectService.triggerSignIn();
      return false;
    }
  }
}
  • 注冊(cè)服務(wù)
  declarations: [
    AppComponent,
    SigninOidcComponent,
    RedirectSilentRenewComponent
  ],
 providers: [
    OpenIdConnectService,
    RequireAuthenticatedUserRouteGuard,
  ],
  • 路由配置
    • app-routing
const routes: Routes = [
  { path: 'blog', loadChildren: './blog/blog.module#BlogModule' },
  { path: 'signin-oidc', component: SigninOidcComponent },
  { path: 'redirect-silentrenew', component: RedirectSilentRenewComponent },
  { path: '**', redirectTo: 'blog' }
];
  • post-routing
const routes: Routes = [
  {
    path: '', component: BlogAppComponent,
    children: [
      { path: 'post-list', component: PostListComponent, canActivate: [RequireAuthenticatedUserRouteGuard] },
      { path: '**', redirectTo: 'post-list' }
    ]
  }
];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,534評(píng)論 19 139
  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    wgl0419閱讀 6,575評(píng)論 1 9
  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,847評(píng)論 2 45
  • 1.打開(kāi)Eclipse,單擊“Window”菜單,選擇下方的“Preferences”。 2.單擊“Server”...
    意中人_Hz閱讀 329評(píng)論 0 1
  • 之前寫(xiě)過(guò)一篇文章是關(guān)于基于NSURLProtocol做的DNS解析,其中對(duì)NSURLProtocol也有了簡(jiǎn)單的介...
    茉莉兒閱讀 28,713評(píng)論 47 103

友情鏈接更多精彩內(nèi)容