首页 > 解决方案 > 如何在 Angular 5 中未经授权使用主页中的实体数据

问题描述

你好我想尝试在主页中未经授权使用实体数据,这是我的一些代码

图表组件

isSaving: boolean;
mass = [];
directions: Direction[];


constructor(private jhiAlertService: JhiAlertService,
            private directionService: DirectionService,
) {
}

ngOnInit() {
    // res: HttpResponse<Direction[]>;
     this.isSaving = false;
    this.directionService.query()
        .subscribe((res: HttpResponse<Direction[]>) => {
            this.directions = res.body;
        }, (res: HttpErrorResponse) => this.onError(res.message));
}


private onError(error: any) {
    this.jhiAlertService.error(error.message, null, null);
}

ChartsComponent.html

<div *ngFor="let d of directions">
{{d.id}} {{d.name}}
</div>

在 home.component.html 我只是打电话<jhi-charts></jhi-charts>

但控制台有错误GET http://localhost:9060/api/directions 401 (Unauthorized)

先感谢您

标签: javaangularangular5jhipster

解决方案


看起来您使用JHipster(按标签)。JHipster在引擎盖下使用Spring Boot,并让您匿名访问某些REST端点,您应该在配置类文件中 - java/config/SecurityConfiguration(它扩展WebSecurityConfigurerAdapter类)提供对它的访问。

找出方法protected void configure(HttpSecurity http),并添加.antMatchers("/api/**").permitAll()以授予权限。

例如,我的配置如下所示:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/admin/login").permitAll()
      .antMatchers("/admin/**").hasAnyAuthority(rolesForAdmin)
      .antMatchers("/subscriber-register/**").permitAll()
    .and()
      .csrf().disable().httpBasic().disable().cors();
}

推荐阅读