簡體   English   中英

如何以角度重定向到身份服務器登錄?

[英]How to be redirected to identity server login in angular?

我想在用戶訪問應用程序時立即重定向到身份服務器。 使用當前設置,我有一個登錄按鈕,點擊后將用戶重定向到 ID 服務器,但我想刪除此按鈕,以便在打開應用程序時發生。

這是我的 app.component.ts 文件

import { OidcSecurityService } from 'angular-auth-oidc-client';

export class AppComponent implements OnInit {

  constructor(private ref: ChangeDetectorRef, public oidcSecurityService: OidcSecurityService) {
  }
  
  ngOnInit() {

    this.oidcSecurityService
    .checkAuth()
    .subscribe((auth) => console.log('is authenticated', auth));
    
  login() {
    this.oidcSecurityService.authorize();
  }
}

以及對應的html

<div>
    <button (click)="login()">Login</button>
</div>

從路由器導入 {Router}。 在玩具構造函數router: Router上設置它router: Router然后

this.oidcSecurityService.checkAuth().subscribe((auth) => router.navigateByUrl('Your URL'); 

您可以通過實現CanActivate 接口在身份驗證保護的幫助下解決您的問題。 如果canActivate返回 false,則取消路由導航,我們可以使用它來授權我們的用戶/將我們的用戶重定向到登錄頁面。

每個需要經過身份驗證的用戶的路由都會在路由定義的 canActivate 屬性中引用您的身份驗證保護。

  { 
    path: 'admin', 
    component: AdminComponent, 
    canActivate: [AuthGuard]
  }

授權守衛:

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
constructor(private oidcSecurityService: OidcSecurityService ) {}

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    return this.oidcSecurityService.checkAuth().pipe(
     tap(isAuthenticated => {
         if (!isAuthenticated) {
             this.oidcSecurityService.authorize();
         }
     })
   );
  }

如果您需要更多幫助,請查看此處的文檔。 盡管文檔沒有提供可觀察的示例。

如果這對你來說是一個有效的選擇,我個人建議切換到 angular-oauth2-oidc。 ( https://www.npmjs.com/package/angular-oauth2-oidc )

然后你可以在 app.component.ts 中做到這一點:

this.oauthService.tryLogin().then((success: boolean) => {
  if (!success) this.oauthService.initCodeFlow();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM