2017-10-17 3 views
4

Azure AD B2C로 암시 적 인증을 올바르게 수행하기 위해 Angular 4 앱을 얻으려고합니다. msal.js를 사용하여 작동 시키려고합니다. 매우 제한된 official sample code을 확인했지만, 로그인을 위해 팝업을 사용하고 리다이렉션을 원하기 때문에 실제로 사용하지는 않습니다.로그인 Azure AD B2C Angular 응용 프로그램과 msal.js에서 사용자를 리디렉션

내가 지금 가지고있는 것은 내 응용 프로그램에 주입하는 모든 인증을 처리해야하는 다음 인증 서비스입니다.

import { Injectable } from '@angular/core'; 
import * as Msal from 'msal'; 

@Injectable() 
export class AuthenticationService { 

    private tenantConfig = { 
     tenant: "example.onmicrosoft.com", 
     clientID: 'redacted (guid of the client), 
     signUpSignInPolicy: "b2c_1_signup", 
     b2cScopes: ["https://example.onmicrosoft.com/demo/read", "openid"] 
    } 

    private authority = "https://login.microsoftonline.com/tfp/" + this.tenantConfig.tenant + "/" + this.tenantConfig.signUpSignInPolicy; 

    private clientApplication: Msal.UserAgentApplication; 

    constructor() { 
     this.clientApplication = new Msal.UserAgentApplication(this.tenantConfig.clientID, this.authority, this.authCallback); 
    } 

    public login(): void { 
     this.clientApplication.loginRedirect(this.tenantConfig.b2cScopes); 
    } 

    public logout(): void { 
     this.clientApplication.logout(); 
    } 

    public isOnline(): boolean { 
     return this.clientApplication.getUser() != null; 
    } 

    public getUser(): Msal.User { 
     return this.clientApplication.getUser(); 
    } 

    public getAuthenticationToken(): Promise<string> { 
     return this.clientApplication.acquireTokenSilent(this.tenantConfig.b2cScopes) 
      .then(token => { 
       console.log("Got silent access token: ", token); 
       return token; 
      }).catch(error => { 
       console.log("Could not silently retrieve token from storage.", error); 
       return this.clientApplication.acquireTokenPopup(this.tenantConfig.b2cScopes) 
        .then(token => { 
         console.log("Got popup access token: ", token); 
         return token; 
        }).catch(error => { 
         console.log("Could not retrieve token from popup.", error); 
         this.clientApplication.acquireTokenRedirect(this.tenantConfig.b2cScopes); 
         return Promise.resolve(""); 
        }); 
      }); 
    } 

    private authCallback(errorDesc: any, token: any, error: any, tokenType: any) { 
     console.log(Callback') 

     if (token) { 
      console.log("Id token", token); 
     } 
     else { 
      console.log(error + ":" + errorDesc); 
     } 

     this.getAuthenticationToken(); 
    } 
} 

하지만 작동하지 않습니다. ID 토큰을 올바르게 가져오고 유효하므로 "Id 토큰"에 제한된 시간 동안 사용할 수있는 값이 표시됩니다.

인증 토큰을 얻으려고하면 문제가 발생합니다. acquireTokenSilent에 대한 첫 번째 호출은 Token renewal operation failed due to timeout: null이라는 오류를 반환합니다.

그러면 사용자 이름과 암호를 묻는 팝업이 나타나는데 잠시 후에 사라지고 오류 메시지가 나타납니다. User does not have an existing session and request prompt parameter has a value of 'None'..

편집 : 다음 https://github.com/Gimly/NetCoreAngularAzureB2CMsal

당신은 홈페이지에서 연결하는 경우

과 : 그래서

, 나는 정확히 무슨 일 당신이 여기에서 얻을 수있는 샘플 응용 프로그램에 문제를 재현하기 위해 이해 생각 fetchData 페이지 (일기 예보가있는 페이지)로 이동하면 인증 토큰이 acquireTokenSilent (브라우저 콘솔을 열어 모든 로그를 가져옴)에 올바르게 바뀌는 것을 볼 수 있습니다. 그러나 fetchData에서 페이지를 직접 새로 고치면 설명 된 것과 동일한 동작을 볼 수 있으며 acquireTokenSilent은 시간 초과에 대한 오류로 실패합니다.

getUser이 올바른 값을 반환하더라도 어떤 이유로 든 getAuthenticationToken을 호출하기 전에 msal이 완전히 초기화되지 않았으므로 완전히 실패한 것입니다.

이제 진짜 질문 ... 토큰을 얻기 전에 완전히 초기화되었는지 어떻게 확인합니까?

+0

[localStorage를 시도한 경우] (https://stackoverflow.com/questions/45201872/how-to-use-localstorage-with-msal-js) 어떻게 될지 궁금합니다. – spottedmahn

+0

@spottedmahn이 방금 시도한 것과 같은 동작입니다. – Gimly

+0

@spottedmahn 문제에 대한 추가 정보를 찾았습니다. 수정 사항을 확인할 수 있습니까? – Gimly

답변

2

OK, 내가 직면 한 문제는 두 가지에 의해 발생되었다

1) 완전히 생성자 호출의 끝에서 완료하지 초기화 프로세스를 발생 msal.js 버그, 그리고 완전히 초기화되기 전에 acquireTokenSilent()으로 전화를 걸었습니다. 이것은 최신 버전에서 수정되었습니다 (아직까지는 프로젝트의 dev 브랜치에 있습니다). See this GitHub issue for more info.

2) 리디렉션 URI가 수정되지 않아 라이브러리에서 현재 URL을 허용 된 리디렉션 URI 목록에 없기 때문에 실패 할 리디렉션 URI로 사용하게되었습니다.

두 가지 문제가 수정 된 후 내가 내 질문에 게시 된 코드가 예상대로 작동하고 있습니다.

+0

당신은 # 1 소스 수 있습니까? 당신은 그것을 연결할 수있는 github 문제가 있습니까? – spottedmahn

+1

@spottedmahn GitHub 문제에 대한 답변을 업데이트했습니다. – Gimly

+0

@Gimly 예를 들어 가져 오기를 추가해 주실 수 있습니까? 예를 따르려하고 있습니다. 인증 서비스의 '출력'디렉토리에있는 파일을 참조하는 msal (0.1.1)의 이전 버전을 사용하고 있습니다. 이것은 더 이상 존재하지 않아서 수입이 효과가 없습니다. – Magrangs

0

MSAL js의 source code을 보면 acquireTokenPopup 대신 acquireTokenRedirect를 사용할 수 있어야합니다.

+0

유효한'id_token'을 가지고 있는데 왜'acquireTokenSilent()'를 호출 할 수 없습니까? 방금 사용자를 로그인하도록 리디렉션했는데 왜 다시 리디렉션해야합니까? – spottedmahn

+1

음, acquireTokenRedirect가 더 잘 작동하지 않는 것 같습니다. 그리고 그것은 @spottedmahn이 말한 것처럼 이중 리디렉션을 생성합니다. – Gimly

+1

@parakh 문제를 재현 할 수있는 자세한 정보와 프로젝트로 내 질문을 업데이트했습니다. – Gimly

관련 문제