2017-11-27 9 views
0

각도 응용 프로그램의 권한 서비스에 역할을 저장하는 데 사용되는 배열에 문제가 있습니다. 나는 로그인에 auth0 서비스를 사용하고 auth.service.ts은 다음과 같습니다. 로그인 handleAuthentication 기능이 호출되고 새로 고침 단추를 클릭 할 때까지 모든 것이 잘 작동됩니다Typescript, Angular4 : 브라우저를 새로 고친 후 배열이 비어 짐

@Injectable() 
export class AuthService { 
    userProfile: any; 
    private roles: string[] = []; 
... 
    public handleAuthentication(): void { 
this.auth0.parseHash((err, authResult) => { 
    if (authResult && authResult.accessToken && authResult.idToken) { 
    window.location.hash = ''; 
    this.setSession(authResult); 
    this.getRoles(authResult); 
    this.router.navigate(['/']); 
    } else if (err) { 
    this.router.navigate(['/']); 
    console.log(err); 
    alert(`Error: ${err.error}. Check the console for further details.`); 
    } 
});} 
//THIS IS getRole function 
private getRoles(authResult){ 
let jwtHelper = new JwtHelper(); 
let decodedToken = jwtHelper.decodeToken(authResult.idToken); 
this.roles = decodedToken['https://tobenorme.com/roles']; 

}

후. 그런 다음 역할 배열이 빈 배열을 반환하고 더 이상 역할을 얻을 수 없습니다. 로컬 저장소에 저장하려고했으나 브라우저에서 편집 할 수 있습니다.

답변

0

JWT 토큰 (https://auth0.com/docs/jwt)을 사용하여 말한 이후로 토큰을 로컬 저장소 또는 쿠키에 안전하게 저장할 수 있습니다. JWT 토큰은 서명되어 브라우저의 모든 로컬 변경 사항이 서버에서 감지되고 모든 API 호출로 토큰을 해독합니다.

로컬 변경을 피할 수는 없지만 서버 측에서는 사용자에게 실제로 제공된 역할/권한이 있는지 항상 확인해야합니다.

0

새로 고침하고 상태가 사라지면 언급 한 것처럼 데이터를 로컬 저장소 나 세션 저장소 (일반 텍스트가 아니라)에 저장하면 응용 프로그램이 다시 부트 스트랩됩니다. 싱글 튼 (singelton)과 같은 방법, 역할이 비어있을 때 http 전화를 걸고 역할이 비어 있지 않을 때 그것을 얻으십시오. RxJs BehaviorSubject를 사용하는 좋은 사례입니다.

0

브라우저에서 로컬 저장소를 사용하도록 설정 한 상태 여야합니다. 값을 저장하려면 localStorage.setItem(name, value)을 사용해야하고 다음에 값을 검색하려면 localStorage.getItem(name)을 사용해야합니다.

0

https://github.com/auth0/angular2-jwt 어쩌면 그것이 내가 이런 식으로 해결 누군가 도움이 될 :

당신은 다음의 예를 참조 할 수

private getRoles(authResult){ 
    let jwtHelper = new JwtHelper(); 
    let decodedToken; 
    if (authResult && authResult.accessToken && authResult.idToken){ 
     decodedToken = jwtHelper.decodeToken(authResult.idToken); 
     this.roles = decodedToken['https://tobenorme.com/roles']; 
    }else if(this.isAuthenticated && authResult){ 
     decodedToken = jwtHelper.decodeToken(authResult); 
     this.roles = decodedToken['https://tobenorme.com/roles']; 
    } 

을 나는 생성자에서이 함수를 호출해야합니다.