Ответ со статусом: 401 Не авторизован для URL. - PullRequest
0 голосов
/ 04 мая 2019

Я пытаюсь следовать этому учебнику .Но я застрял в этой части Защищаем Backend API с помощью Okta .

Я получаю следующую ошибку Ответ со статусом: 401 Не авторизован для URL: http://localhost:8000/api/players

Я уже установил http://localhost:4200 в качестве доверенного источника в учетной записи okta.

Вот мой код

AuthenticateWithOkta.php из приложения Laravel

namespace App\Http\Middleware;

use Closure;

class AuthenticateWithOkta
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->isAuthorized($request)) {
            return $next($request);
        } else {
            return response('Unauthorized.', 401);
        }
    }

    public function isAuthorized($request)
    {
        if (! $request->header('Authorization')) {
            return false;
        }

        $authType = null;
        $authData = null;

        // Extract the auth type and the data from the Authorization header.
        @list($authType, $authData) = explode(" ", $request->header('Authorization'), 2);

        // If the Authorization Header is not a bearer type, return a 401.
        if ($authType != 'Bearer') {
            return false;
        }

        // Attempt authorization with the provided token
        try {

            // Setup the JWT Verifier
            $jwtVerifier = (new \Okta\JwtVerifier\JwtVerifierBuilder())
                            ->setAdaptor(new \Okta\JwtVerifier\Adaptors\SpomkyLabsJose())
                            ->setAudience('api://default')
                            ->setClientId('{HERE MY CLIENT ID}')
                            ->setIssuer('https://dev-{MY ISSUER NUMBERS}.okta.com/oauth2/default')
                            ->build();

            // Verify the JWT from the Authorization Header.
            $jwt = $jwtVerifier->verify($authData);
        } catch (\Exception $e) {

            // We encountered an error, return a 401.
            return false;
        }

        return true;
    }

}

.module.ts из Angular

import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { TriviaGameComponent } from './trivia-game/trivia-game.component';

import { Routes, RouterModule } from '@angular/router';
import { OktaAuthModule, OktaCallbackComponent } from '@okta/okta-angular';

import { HttpModule } from '@angular/http';

const routes: Routes = [
    { path: '', component: HomeComponent, pathMatch: 'full' },
    { path: 'trivia', component: TriviaGameComponent },
    { path: 'implicit/callback', component: OktaCallbackComponent },
    { path: '**', redirectTo: '', pathMatch: 'full' },
];

const oktaConfig = {
  issuer: 'https://dev-{ISSUER NUMBERS}.okta.com/oauth2/default',
  redirectUri: 'http://localhost:4200/implicit/callback',
  clientId: '{CLIENT ID}'
};

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    TriviaGameComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    RouterModule.forRoot(routes),
    OktaAuthModule.initAuth(oktaConfig)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

player.service.ts из Angular

import { OktaAuthService } from '@okta/okta-angular';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';

export interface Player {
    id: Number,
    name: String,
    answers: Number,
  points: number,
  isUpdating: boolean,
}

const API_URL: string = 'http://localhost:8000';

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

    private accessToken;
    private headers;

    constructor(private oktaAuth: OktaAuthService, private http: Http) {
        this.init();
    }

    async init() {
        this.accessToken = await this.oktaAuth.getAccessToken();
        this.headers = new Headers({
            Authorization: 'Bearer ' + this.accessToken
        });
    }

    getPlayers(): Observable<Player[]> {
        return this.http.get(API_URL + '/api/players',
            new RequestOptions({ headers: this.headers })
        )
        .map(res => {
          let modifiedResult = res.json().data
                modifiedResult = modifiedResult.map(function(player) {
            player.isUpdating = false;
            return player;
          });
          return modifiedResult;
        });
    }
}

Может кто-нибудь следовать учебнику и проверить, появляется ли ошибка?


ОБНОВЛЕНИЕ

Я решил свою проблему, нашел много проблем с печатью ($ e) в конце этого файла AuthenticateWithOkta.php

  1. пара из них были относительно обновления послестроки в php.ini

curl.cainfo = "D: \ xampp \ php \ extras \ ssl \ cacert.pem" openssl.cafile = "D: \ xampp \ php \ extras \ ssl \cacert.pem "

Другой вопрос касался переключения этой части

-> setAdaptor (new \ Okta \ JwtVerifier \ Adapters \ SpomkyLabsJose () для этого

-> setAdaptor (new \ Okta \JwtVerifier \ Adapters \ FirebasePhpJwt ())

И последняя проблема была о CORS и добавлении правильного заголовка в запрос
...