#angular #command-line-interface #npm-install #auth0
Вопрос:
Я работаю над аутентификацией в Angular с использованием auth0. Я уже установил auth0, auth0-js И auth0-react, и мое приложение по-прежнему не загружается. Интерфейс командной строки продолжает выдавать мне эту ошибку:
./src/приложение/службы/auth.service.ts:2:0-34 — Ошибка: Модуль не найден: Ошибка: Не удается разрешить «auth0-js» в «C:UsersOwnerDesktopcoding_course_docsAngularAudioPlayersrcappservices’
Мне интересно, правильно ли установлен необходимый пакет или что-то в этом роде.
Вот мой pacakge.json:
{
"name": "angular-audio-player",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "~12.2.0",
"@angular/cdk": "^12.2.9",
"@angular/common": "~12.2.0",
"@angular/compiler": "~12.2.0",
"@angular/core": "~12.2.0",
"@angular/forms": "~12.2.0",
"@angular/material": "^12.2.9",
"@angular/platform-browser": "~12.2.0",
"@angular/platform-browser-dynamic": "~12.2.0",
"@angular/router": "~12.2.0",
"@auth0/auth0-angular": "^1.7.0",
"@auth0/auth0-react": "^1.8.0",
"@types/auth0-js": "^9.14.5",
"moment": "^2.29.1",
"rxjs": "~6.6.0",
"tslib": "^2.3.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~12.2.4",
"@angular/cli": "~12.2.4",
"@angular/compiler-cli": "~12.2.0",
"@types/jasmine": "~3.8.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.8.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
"node-scss": "^7.0.3",
"ts-jest": "^27.0.7",
"typescript": "~4.3.5"
}
}
Вот tsconfig:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "es2017",
"module": "es2020",
"lib": [
"es2018",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
and here’s the tsconfig.app:
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
],
"exclude": [
"**/*.spec.ts"
]
}
вот также файл auth.service:
import { Injectable } from '@angular/core';
//npm install --save @types/auth0-js (CLI cmd)
import * as auth0 from 'auth0-js';
import { environment } from '../../environments/environment';
import{
Observable,
BehaviorSubject,
bindNodeCallback,
of
} from 'rxjs';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthService {
//instance of auth0-WebAuth that is used for authentication
auth0 = new auth0.WebAuth({
clientID: environment.auth0.clientID,
domain: environment.auth0.domain,
responseType: 'token id_token',
scope: 'openid profile email'
});
//'localStorage' keys (for storing authentication and user profile data) that track whether or not to renew token
private _authFlag = 'isLoggedIn';
private _userProfileFlag = 'userProfile';
//'Observable' that stores authentication data amp; emits access token
token$!: Observable<string>;
//'BehaviorSubject' that creates stream for user profile data
userProfile$ = new BehaviorSubject<any>(null);
//Authentication Navigation
onAuthSuccessUrl = '/';
onAuthFailureUrl = '/';
logoutUrl = environment.auth0.logoutUrl;
/*parseHash$ =
After authentication occurs, you can use the parseHash method to parse a URL hash fragment
when the user is redirected back to your application in order to extract
the result of an Auth0 authentication response*/
//Create observable of Auth0, then parseHash() function to gather 'auth' results
parseHash$ = bindNodeCallback(this.auth0.parseHash.bind(this.auth0));
//Create observable of Auth0 checkSession() function to verify authorization server session and renew tokens
checkSession$ = bindNodeCallback(this.auth0.checkSession.bind(this.auth0));
constructor(private router: Router) {
//'get' user info from 'localStorage'
const userProfile = localStorage.getItem(this._userProfileFlag);
//checks if there is any user info stored
if (userProfile) {
//if there IS user info stored, emit it via the 'userProfile
Любая помощь в том, как заставить приложение работать, приветствуется!
Комментарии:
1. Привет, можете ли вы прикрепить auth.service.ts к вопросу? Спасибо.
2. Теперь он там.
Ответ №1:
Я думаю, что вы используете неправильную упаковку. попробуйте сделать npm install @auth0/auth0-angular
, и то, что вы ищете, является auth0-угловым, найдите это здесь.
Комментарии:
1. кажется, это работает. единственное, что WebAuth (), похоже, не находится в библиотеке импорта auth0-angular, что приводит к еще одной ошибке.
BehaviorSubject
this.userProfile$.next(JSON.parse(userProfile));
}
}
//authorize user
login = () => this.auth0.authorize();
/*
uses the parseHash$ 'Observable' to parse the auth result,
then sets authentication state using 'this._setAuth()', takes 'authResult' from parsed Auth data, and initializes 'tokenЛюбая помощь в том, как заставить приложение работать, приветствуется!
Комментарии:
1. Привет, можете ли вы прикрепить auth.service.ts к вопросу? Спасибо.
2. Теперь он там.
Ответ №1:
Я думаю, что вы используете неправильную упаковку. попробуйте сделать npm install @auth0/auth0-angular
, и то, что вы ищете, является auth0-угловым, найдите это здесь.
Комментарии:
1. кажется, это работает. единственное, что WebAuth (), похоже, не находится в библиотеке импорта auth0-angular, что приводит к еще одной ошибке.
,
then redirects to 'onAuthSuccessUrl'
*/
handleLoginCallback = () => {
if (window.location.hash amp;amp; !this.authenticated) {
//parse authResult from Observable
this.parseHash$().subscribe({
next: authResult => {
//takes authResult from parsed Auth data sets authentication state
this._setAuth(authResult);
window.location.hash = '';
//redirect to 'onAuthSuccessUrl'
this.router.navigate([this.onAuthSuccessUrl]);
},
error: err => this._handleError(err)
});
}
};
//Save authentication data and update login status subject
private _setAuth = (authResult: any) => {
//take authResult from parsed Auth data and initialize 'tokenЛюбая помощь в том, как заставить приложение работать, приветствуется!
Комментарии:
1. Привет, можете ли вы прикрепить auth.service.ts к вопросу? Спасибо.
2. Теперь он там.
Ответ №1:
Я думаю, что вы используете неправильную упаковку. попробуйте сделать npm install @auth0/auth0-angular
, и то, что вы ищете, является auth0-угловым, найдите это здесь.
Комментарии:
1. кажется, это работает. единственное, что WebAuth (), похоже, не находится в библиотеке импорта auth0-angular, что приводит к еще одной ошибке.
Observable
this.token$ = of(authResult.accessToken);
const userProfile = authResult.idTokenPayload;
//Emit value for user data subject
this.userProfile$.next(userProfile);
//save 'userProfile' in 'localStorage'
localStorage.setItem(this._userProfileFlag, JSON.stringify(userProfile));
//Set flag in local storage stating that this app is logged in
localStorage.setItem(this._authFlag, JSON.stringify(true));
const renewAuth = () => {
//checks if user is authenticated or not
if (this.authenticated) {
//checkSession to see if 'authResult' is valid
this.checkSession$({}).subscribe({
next: authResult => this._setAuth(authResult),
error: err => {
localStorage.removeItem(this._authFlag);
localStorage.removeItem(this._userProfileFlag);
this.router.navigate([this.onAuthFailureUrl]);
}
});
}
}
const logout = () => {
//Set authentication status flag in local storage to false
localStorage.setItem(this._authFlag, JSON.stringify(false));
//remove the userProfile data
localStorage.removeItem(this._userProfileFlag);
//refresh, then redirect to homepage
this.auth0.logout({
returnTo: this.logoutUrl,
clientID: environment.auth0.clientID
});
};
}
//checks if user is authenticated or not using 'localStorage' flag
get authenticated(): boolean {
return JSON.parse(localStorage.getItem(this._authFlag) || '{}');
}
//Utility functions
private _handleError = (err: { error_description: any; }) => {
if (err.error_description) {
console.error(`Error: ${err.error_description}`);
} else {
console.error(`Error: ${JSON.stringify(err)}`);
}
};
}
Любая помощь в том, как заставить приложение работать, приветствуется!
Комментарии:
1. Привет, можете ли вы прикрепить auth.service.ts к вопросу? Спасибо.
2. Теперь он там.
Ответ №1:
Я думаю, что вы используете неправильную упаковку. попробуйте сделать npm install @auth0/auth0-angular
, и то, что вы ищете, является auth0-угловым, найдите это здесь.
Комментарии:
1. кажется, это работает. единственное, что WebAuth (), похоже, не находится в библиотеке импорта auth0-angular, что приводит к еще одной ошибке.