从角度项目到Jhipster的jwt连接 [英] jwt connection from angular project to jhipster

查看:44
本文介绍了从角度项目到Jhipster的jwt连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有角度的基础项目和一个简单的微服务jhipster项目.因为我在jhipster项目中选择了jwt选项,所以我想使用我的angular项目中的方法.在寻找了几个小时后,我终于找到了这段代码,该代码可以帮助我成功连接,但是却出现了一个怪异的错误,使我大失所望.这是我用来尝试连接和使用jhipster方法的角度类:

auth-interceptor.ts文件

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(private token: TokenStorageService) { }

intercept(req: HttpRequest<any>, next: HttpHandler) {
    let authReq = req;
    const token = this.token.getToken();
    if (token != null) {
        authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });
    }
    return next.handle(authReq);
  }
 }

 export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];

auth.service.ts

 const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };



 @Injectable({
  providedIn: 'root'
  })
  export class AuthService {

      private loginUrl = 'http://localhost:8082/api/authenticate';
      private signupUrl = 'http://localhost:8080/api/auth/signup';

      constructor(private http: HttpClient) {
      }

      attemptAuth(credentials: AuthLoginInfo): Observable<JwtResponse> {
       return this.http.post<JwtResponse>(this.loginUrl, credentials, httpOptions);
        }

       signUp(info: SignUpInfo): Observable<string> {
    return this.http.post<string>(this.signupUrl, info, httpOptions);
       }
     }

jwt-response.ts

export class JwtResponse {
   accessToken: string;
   type: string;
    username: string;
   authorities: string[];
  }

token-storage.service.spec.ts

describe('TokenStorageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
    providers: [TokenStorageService]
   });
   });

   it('should be created', inject([TokenStorageService], (service: TokenStorageService) => {
     expect(service).toBeTruthy();
   }));
  });

token.storage.service.ts

  const TOKEN_KEY = 'AuthToken';
     const USERNAME_KEY = 'AuthUsername';
     const AUTHORITIES_KEY = 'AuthAuthorities';

     @Injectable({
  providedIn: 'root'
})
export class TokenStorageService {
  private roles: Array<string> = [];
  constructor() { }

  signOut() {
    window.sessionStorage.clear();
  }

  public saveToken(token: string) {
    window.sessionStorage.removeItem(TOKEN_KEY);
    window.sessionStorage.setItem(TOKEN_KEY, token);
  }

  public getToken(): string {
    return sessionStorage.getItem(TOKEN_KEY);
  }

  public saveUsername(username: string) {
    window.sessionStorage.removeItem(USERNAME_KEY);
    window.sessionStorage.setItem(USERNAME_KEY, username);
  }

  public getUsername(): string {
    return sessionStorage.getItem(USERNAME_KEY);
  }

  public saveAuthorities(authorities: string[]) {
    window.sessionStorage.removeItem(AUTHORITIES_KEY);
    window.sessionStorage.setItem(AUTHORITIES_KEY, JSON.stringify(authorities));
  }

  public getAuthorities(): string[] {
    this.roles = [];

    if (sessionStorage.getItem(TOKEN_KEY)) {
      JSON.parse(sessionStorage.getItem(AUTHORITIES_KEY)).forEach(authority => {
        this.roles.push(authority.authority);
      });
       }

       return this.roles;
      }
     }

最后这是我的连接方法:

onSubmit() {
    console.log(this.form);

    this.loginInfo = new AuthLoginInfo(
      this.form.username,
      this.form.password);

    this.authService.attemptAuth(this.loginInfo).subscribe(
      data => {
        this.tokenStorage.saveToken(data.accessToken);
        this.tokenStorage.saveUsername(data.username);
        this.tokenStorage.saveAuthorities(data.authorities);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.roles = this.tokenStorage.getAuthorities();
        this.reloadPage();
      },
      error => {
        console.log(error);
        this.errorMessage = error.error.message;
        this.isLoginFailed = true;
      }
    );
  }

有了这个,我能够成功登录,但是一旦我登录后,尝试执行其他任何操作时都会收到此错误:

core.js:6014 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at TokenStorageService.getAuthorities (token-storage.service.ts:45)

如果您知道使用jwt从angular连接到jhipster的任何简单方法,请帮助我,因为我在这里被封锁了,我有一个完整的jhipster项目,我不能消耗任何..

解决方案

好吧,看来您的服务器未在JWT响应中提供authorities.由于缺少数据,因此saveAuthorities保存了字符串"undefined",该字符串以后无法使用.

如果缺少authorities的原因是您盲目地从互联网上复制了一些随机代码,请从class JwtResponsesaveAuthoritiesgetAuthorities及其所有引用中删除authorities.

否则,只需在响应中提供authorities.

或者您可以在将权限保存在onSubmit回调中时检查权限是否存在.

if (data.authorities)
    this.tokenStorage.saveAuthorities(data.authorities);

i have an angular basic project and a simple microservice jhipster project. since i chosed jwt option in my jhipster project , i want to consume methods from my angular project.after looking for hours i finnaly found this code which helped me to connect successfuly but i get a weird error which bloked me. here is my angular classes i used to try connect and consume jhipster methods:

auth-interceptor.ts file

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

constructor(private token: TokenStorageService) { }

intercept(req: HttpRequest<any>, next: HttpHandler) {
    let authReq = req;
    const token = this.token.getToken();
    if (token != null) {
        authReq = req.clone({ headers: req.headers.set(TOKEN_HEADER_KEY, 'Bearer ' + token) });
    }
    return next.handle(authReq);
  }
 }

 export const httpInterceptorProviders = [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
];

auth.service.ts

 const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };



 @Injectable({
  providedIn: 'root'
  })
  export class AuthService {

      private loginUrl = 'http://localhost:8082/api/authenticate';
      private signupUrl = 'http://localhost:8080/api/auth/signup';

      constructor(private http: HttpClient) {
      }

      attemptAuth(credentials: AuthLoginInfo): Observable<JwtResponse> {
       return this.http.post<JwtResponse>(this.loginUrl, credentials, httpOptions);
        }

       signUp(info: SignUpInfo): Observable<string> {
    return this.http.post<string>(this.signupUrl, info, httpOptions);
       }
     }

jwt-response.ts

export class JwtResponse {
   accessToken: string;
   type: string;
    username: string;
   authorities: string[];
  }

token-storage.service.spec.ts

describe('TokenStorageService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
    providers: [TokenStorageService]
   });
   });

   it('should be created', inject([TokenStorageService], (service: TokenStorageService) => {
     expect(service).toBeTruthy();
   }));
  });

token.storage.service.ts

  const TOKEN_KEY = 'AuthToken';
     const USERNAME_KEY = 'AuthUsername';
     const AUTHORITIES_KEY = 'AuthAuthorities';

     @Injectable({
  providedIn: 'root'
})
export class TokenStorageService {
  private roles: Array<string> = [];
  constructor() { }

  signOut() {
    window.sessionStorage.clear();
  }

  public saveToken(token: string) {
    window.sessionStorage.removeItem(TOKEN_KEY);
    window.sessionStorage.setItem(TOKEN_KEY, token);
  }

  public getToken(): string {
    return sessionStorage.getItem(TOKEN_KEY);
  }

  public saveUsername(username: string) {
    window.sessionStorage.removeItem(USERNAME_KEY);
    window.sessionStorage.setItem(USERNAME_KEY, username);
  }

  public getUsername(): string {
    return sessionStorage.getItem(USERNAME_KEY);
  }

  public saveAuthorities(authorities: string[]) {
    window.sessionStorage.removeItem(AUTHORITIES_KEY);
    window.sessionStorage.setItem(AUTHORITIES_KEY, JSON.stringify(authorities));
  }

  public getAuthorities(): string[] {
    this.roles = [];

    if (sessionStorage.getItem(TOKEN_KEY)) {
      JSON.parse(sessionStorage.getItem(AUTHORITIES_KEY)).forEach(authority => {
        this.roles.push(authority.authority);
      });
       }

       return this.roles;
      }
     }

and finnaly this is my connection method:

onSubmit() {
    console.log(this.form);

    this.loginInfo = new AuthLoginInfo(
      this.form.username,
      this.form.password);

    this.authService.attemptAuth(this.loginInfo).subscribe(
      data => {
        this.tokenStorage.saveToken(data.accessToken);
        this.tokenStorage.saveUsername(data.username);
        this.tokenStorage.saveAuthorities(data.authorities);

        this.isLoginFailed = false;
        this.isLoggedIn = true;
        this.roles = this.tokenStorage.getAuthorities();
        this.reloadPage();
      },
      error => {
        console.log(error);
        this.errorMessage = error.error.message;
        this.isLoginFailed = true;
      }
    );
  }

with this i am able to login successfully but once i login i get this error when i try to do anything else:

core.js:6014 ERROR SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at TokenStorageService.getAuthorities (token-storage.service.ts:45)

Guys if u know any simple method to connect to jhipster using jwt from angular please help me cause i am blocked here , i have a full jhipster project which i cant consume any..

解决方案

Well, seems your server does not provide authorities in the JWT response. Since the data is missing, the saveAuthorities saves string "undefined" that cannot be served later.

If the reason authorities is missing is that you blindly copied some random code off the internet, delete the authorities from class JwtResponse and saveAuthorities, getAuthorities and all references to them.

Otherwise, just provide the authorities in your response.

Or you can check if authorities exist when saving them in onSubmit callback.

if (data.authorities)
    this.tokenStorage.saveAuthorities(data.authorities);

这篇关于从角度项目到Jhipster的jwt连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆