HttpClient的授权标头返回null,尝试了研究中的所有方法,但它们均不起作用

时间:2019-05-06 10:13:48

标签: angular typescript httpclient authhttp

我有一个虚假的后端服务,该教程提供了该服务,但是该教程的棱角分明的版本很旧。我决定使用新版本的angular和auth0 / jwt,但这与本教程所教的内容完全不同。我无法解决授权标头返回null的问题,即使我在app.module中有JwtModule.forRoot

我尝试做console.log(connection.request.headers.get('Authorization'));,但返回的是空值

这是我的代码: order.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class OrderService {

  constructor(private http: HttpClient) {
  }

  getOrders() {
    return this.http.get('/api/orders');
  }
}

fake-backend.ts

import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { HttpClient } from '@angular/common/http';

export function fakeBackendFactory(
    backend: MockBackend, 
    options: BaseRequestOptions) {

  let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ik1vc2ggSGFtZWRhbmkiLCJhZG1pbiI6dHJ1ZSwiZXhwIjoxMTExMTExMTExMX0.MkMCCNb5PMF-vdgpJTH0ZxFXeSPn0lJGyNBWkIJDzqE';

  backend.connections.subscribe((connection: MockConnection) => {
    // We are using the setTimeout() function to simulate an 
    // asynchronous call to the server that takes 1 second. 
    setTimeout(() => {
 // 
       // Fake implementation of /api/orders
       //
       if (connection.request.url.endsWith('/api/orders') && 
           connection.request.method === RequestMethod.Get) {
         if (connection.request.headers.get('Authorization') === 'Bearer ' + token) {
            connection.mockRespond(new Response(
              new ResponseOptions({ status: 200, body: [1, 2, 3] })
          ));
          } else {
           connection.mockRespond(new Response(
             new ResponseOptions({ status: 401 })
           ));
          }
        }



    }, 1000);
  });

  return new Http(backend, options);
}

export let fakeBackendProvider = {
    provide: HttpClient,
    useFactory: fakeBackendFactory,
    deps: [MockBackend, BaseRequestOptions]
};

app.module.ts

import { OrderService } from './services/order.service';
import { MockBackend } from '@angular/http/testing';
import { fakeBackendProvider } from './helpers/fake-backend';
import { AuthService } from './services/auth.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule, Http, BaseRequestOptions } from '@angular/http';
import { JwtModule, JWT_OPTIONS } from '@auth0/angular-jwt';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { RouterModule } from '@angular/router'; 

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { LoginComponent } from './login/login.component';
import { SignupComponent } from './signup/signup.component';
import { AdminComponent } from './admin/admin.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { NoAccessComponent } from './no-access/no-access.component';
import { AuthGuard } from './services/auth-guard.service';
import { AdminAuthGuard } from './services/admin-auth-guard.service';

export function tokenGetter(){
  return localStorage.getItem('token');
}

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    SignupComponent,
    AdminComponent,
    HomeComponent,
    NotFoundComponent,
    NoAccessComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    HttpClientModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent },
      {
        path: 'admin',
        component: AdminComponent, 
        canActivate: [AuthGuard, AdminAuthGuard]
      },
      { path: 'login', component: LoginComponent },
      { path: 'no-access', component: NoAccessComponent }
    ]),
    JwtModule.forRoot({
      config: { tokenGetter,
      whitelistedDomains: ['http://localhost:4200'],
      blacklistedRoutes: [],
      headerName: 'Authorization',
      throwNoTokenError: true,
      skipWhenExpired: false,
      authScheme: 'Bearer '
      }
    })
  ],
  providers: [
    OrderService,

    AuthService,
    AuthGuard,
    AdminAuthGuard,

    // For creating a mock back-end. You don't need these in a real app. 
    fakeBackendProvider,
    MockBackend,
    BaseRequestOptions,
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

admin.component.ts

import { OrderService } from './../services/order.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html',
  styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
  orders: any[];

  constructor(private orderService: OrderService) { }

  ngOnInit() {
    this.orderService.getOrders()
      .subscribe(orders => this.orders = <any[]>orders);
  }
}

connection.request.headers.get('Authorization')实际上返回null,那么如何才能将授权标头真正更改为'Bearer ' + token呢?我已经使用了2天了.....它仍然无法解决,我只想实现AuthHttp之类的东西

1 个答案:

答案 0 :(得分:0)

我认为您应该像这样在服务中设置标题

class TagsAdapter : RecyclerView.Adapter<TagsAdapter.TagHolder>() {

    private var baseList: MutableList<BaseTag> = ArrayList()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TagHolder {
        val itemView = LayoutInflater.from(parent.context)
                .inflate(R.layout.tag_item, parent, false)
        return TagHolder(itemView)
    }

    override fun onBindViewHolder(holder: TagHolder, position: Int) {
        val tag = baseList[position]
        holder.tvAlias.text = tag.content
        holder.tvDate.text = tag.date?.let { AppUtils.toDate(it) }
        holder.ivType.background = tag.type?.let { getDrawable(it) }
    }

    override fun getItemCount(): Int {
        return baseList.size
    }

    fun setTags(list: List<BaseTag>) {
        if (this.baseList.isEmpty()) {
            this.baseList = list as MutableList<BaseTag>
        } else {
            this.baseList.addAll(list)
        }
        orderList()
        notifyDataSetChanged()
    }

    private fun getDrawable(type: String): Drawable? {
        when (type) {
            AppConstants.TYPE_TEXT -> return ContextCompat.getDrawable(App.instance, R.drawable.ic_text)
            AppConstants.TYPE_EMAIL -> return ContextCompat.getDrawable(App.instance, R.drawable.ic_write)
            AppConstants.TYPE_URL -> return ContextCompat.getDrawable(App.instance, R.drawable.ic_clean)
            AppConstants.TYPE_PHONE -> return ContextCompat.getDrawable(App.instance, R.drawable.ic_mobile)
            AppConstants.TYPE_LAUNCHER -> return ContextCompat.getDrawable(App.instance, R.drawable.ic_code)
        }
        return null
    }

    private fun orderList(){
        baseList.sortBy { it.date }
        baseList.reverse()
    }

    fun clear(){
        this.baseList.clear()
    }

    inner class TagHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvAlias: TextView = itemView.findViewById(R.id.txtAlias)
        var tvDate: TextView = itemView.findViewById(R.id.txtDate)
        var ivType: ImageView = itemView.findViewById(R.id.ivType)
    }
}