- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
使用 ASP.NET Core API 应用程序登录到 Angular 应用程序后,出现以下错误
Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[AuthGuard]: StaticInjectorError(Platform: core)[AuthGuard]: NullInjectorError: No provider for AuthGuard!
login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { routerTransition } from '../router.animations';
import { FormBuilder, FormGroup, Validators, ReactiveFormsModule } from '@angular/forms';
import { first } from 'rxjs/operators';
import { AlertService, AuthenticationService } from '../_services';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
constructor(private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService) {}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
// reset login status
this.authenticationService.logout();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.authenticationService.login(this.f.username.value, this.f.password.value)
.pipe(first())
.subscribe(
data => {
this.router.navigate([this.returnUrl]);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
AuthenticationService.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
@Injectable()
export class AuthenticationService {
constructor(private http: HttpClient) { }
login(username: string, password: string) {
return this.http.post<any>
(`http://localhost:5000/api/employee/authenticate`, { UserName: username,
Password: password })
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// store user details and jwt token in local storage to
keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
}));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
}
雇员 Controller
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class EmployeeController : ControllerBase
{
private IEmployeeService _employeeService;
private IMapper _mapper;
private readonly AppSettings _appSettings;
public EmployeeController(
IEmployeeService employeeService,
IMapper mapper,
IOptions<AppSettings> appSettings)
{
_employeeService = employeeService;
_mapper = mapper;
_appSettings = appSettings.Value;
}
[AllowAnonymous]
[HttpPost("authenticate")]
public IActionResult Authenticate([FromBody]EmployeeDto employeeDto)
{
var employee = _employeeService.Authenticate(employeeDto.UserName, employeeDto.Password);
if (employee == null)
return BadRequest(new { message = "UserName or Password is incorrect" });
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, employee.IdMyUser.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
employee.IdMyUserNavigation = new MyUserService().GetById(employee.IdMyUser);
// return basic employee info (without password) and token to store client side
return Ok(new
{
Id = employee.IdMyUser,
UserName = employee.UserName,
FirstName = employee.IdMyUserNavigation.Fname,
LastName = employee.IdMyUserNavigation.Lname,
Token = tokenString
});
}
/// <summary>
/// Get idCommune and creating and setting a list of contacts,
/// Creating the user and setting the forieng key to employee,
/// Add idPosition to the employee.
/// Save the Employee
/// </summary>
/// <param name="employeeDto">
/// MyUser{
/// Fname, Lname, rue,
/// CommuneDto{
/// Commune
/// WilayaDto{
/// Wilaya
/// }
/// }
/// ContactsDtos:[ {ContactType, ContactInfo, IsPrimary} ... ]
/// }
/// UserName, Password, BirthDate, Salary,
/// PositionDto{
/// Posititon, BaseSalary
/// }
/// </param>
/// <returns>HTTP 200 OK(employee)</returns>
[AllowAnonymous]
[HttpPost("register")]
public IActionResult Register([FromBody]EmployeeDto employeeDto)
{
// map dto to entity
var employee = _mapper.Map<Employee>(employeeDto);
var user = _mapper.Map<MyUser>(employeeDto.myUser);
try
{
IMyUserService _myUserService = new MyUserService();
IPositionService _positionService = new PositionService();
ICommuneService _communeService = new CommuneService();
// Set idCommune for the user.
user.IdCommune = _communeService.GetByName(employeeDto.myUser.communeDto.Commune).IdCommune;
// Set the list of Contacts for the user.
foreach (var contactDto in employeeDto.myUser.ContactsDtos)
{
Contact contact = new Contact();
contact.ContactInfo = contactDto.ContactInfo;
contact.ContactType = contactDto.ContactType;
contact.IsPrimary = contactDto.IsPrimary.ToString();
user.Contact.Add(contact);
}
// Save the User.
user = _myUserService.Create(user);
// Set the idMyUser for the employee.
employee.IdMyUser = user.IdMyUser;
// Set the idPosition for the employee.
employee.IdPosition = _positionService.GetByName(employeeDto.positionDto.Position).IdPosition;
//Create and Save the employee
var e = _employeeService.Create(employee, employeeDto.Password);
// Return HTTP 200 OK requet with the employee JSON.
return Ok(e);
}
catch (AppException ex)
{
// return error message if there was an exception
return BadRequest(new { message = ex.Message });
}
}
[HttpGet]
public IActionResult GetAll()
{
var employees = _employeeService.GetAll();
var employeeDtos = _mapper.Map<IList<EmployeeDto>>(employees);
return Ok(employeeDtos);
}
[HttpGet("{id}")]
public IActionResult GetById(int id)
{
var employee = _employeeService.GetById(id);
var employeeDto = _mapper.Map<EmployeeDto>(employee);
return Ok(employeeDto);
}
[HttpPut("{id}")]
public IActionResult Update(int id, [FromBody]EmployeeDto employeeDto)
{
// map dto to entity and set id
var employee = _mapper.Map<Employee>(employeeDto);
employee.IdMyUser = id;
try
{
// save
_employeeService.Update(employee, employeeDto.Password);
return Ok();
}
catch (AppException ex)
{
// return error message if there was an exception
return BadRequest(new { message = ex.Message });
}
}
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
_employeeService.Delete(id);
return Ok();
}
}
app.module.ts
import { CommonModule } from '@angular/common';
import { HttpClient, HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AlertComponent } from './_directives';
import { AuthGuard } from './_guards';
import { JwtInterceptor, ErrorInterceptor } from './_helpers';
import { AlertService, AuthenticationService, UserService } from './_services';
// AoT requires an exported function for factories
export const createTranslateLoader = (http: HttpClient) => {
/* for development
return new TranslateHttpLoader(
http,
'/start-angular/SB-Admin-BS4-Angular-6/master/dist/assets/i18n/',
'.json'
); */
return new TranslateHttpLoader(http, './assets/i18n/', '.json');
};
@NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient]
}
}),
AppRoutingModule
],
declarations: [
AppComponent,
AlertComponent,
],
providers: [
AuthGuard,
AlertService,
AuthenticationService,
UserService,
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
bootstrap: [AppComponent]
})
export class AppModule {}
auth.guard.ts
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from
'@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (localStorage.getItem('currentUser')) {
// logged in so return true
return true;
}
// not logged in so redirect to login page with the return url
this.router.navigate(['login'], { queryParams: { returnUrl: state.url
}});
return false;
}
}
最佳答案
尝试将此添加到您的 AuthGuard
@Injectable({providedIn: "root"})
或在此处指定您的 auth guard 服务的确切位置
import { AuthGuard } from './_guards';
关于c# - StaticInjectorError(AppModule)[AuthGuard] 登录后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53770708/
我正在尝试为我的用户提供使用 Google 或 Facebook 登录的选项。到目前为止,我找到了一个实现 Google 登录流程的示例,但如果我可以在同一 Activity 中实现类似的 Faceb
我有一个网页,它对用户是否登录很敏感。我使用的是 Google 登录 Javascript SDK。当用户到达此页面时,我想显示一个插页式广告(“正在加载...”),然后 1)如果用户已登录则呈现页面
我用 digitalocean 创建了一个 droplet,并使用 apt install mariadb-server 命令安装了 mariadb。现在我想使用 php 连接到我的服务器,我使用这个
这个问题在这里已经有了答案: Inno Setup - Signing fails with "Sign Tool failed with exit code 0x1" (2 个回答) 3年前关闭。
我正在尝试使用他们的新 API 实现 google 登录:https://developers.google.com/identity/sign-in/web/ 登录和注销工作正常。我的问题是我不知道
我的应用程序具有谷歌登录、Facebook 登录和 braintree 集成。 我已将以下代码放入 appdelegate.swift 中: func application(_ applicatio
我有一个 Flask 应用程序,最近在我的登录/退出表单中实现了 Flask-Login: @account.route('/sign-in', methods=['POST', 'GET']) de
friend 们,我是初学者级别的 ios swift 学习者。我一直在尝试在我的试用应用程序中进行谷歌登录。根据来自谷歌开发人员和其他教程的资源,我成功地使用 UIView 进行了登录。然后我试图在
我正在使用 Ionic 在 Codeigniter/Ion_Auth/codeigniter-restclient 之上构建登录系统,当我尝试从“ionic 服务器”登录时,登录可以正常工作,但对 L
在 Docker 文件中我有这个 FROM ubuntu RUN apt update && apt -y upgrade RUN apt install -y sudo # Setup ops us
对于 Java 开发,我使用 Slf4j 和 Logback。 Logger logger = LoggerFactory.getLogger(HelloWorld.class); logger.de
在 Scala 应用程序中进行日志记录的好方法是什么?与语言哲学一致的东西,不会使代码困惑,并且维护成本低且不引人注目。以下是基本要求列表: 简单 不会使代码困惑。 Scala 以其简洁而著称。我不希
我正在尝试将我的登录名转换为 Retrofit2 我的旧 LoginActivity: public class LoginActivity extends Activity { private st
我正在尝试让 google+ 登录在 android 上运行。我的问题是,每当我使用 eclipse 运行它时,google 开发站点上提供的示例都能完美运行。当我签署 apk 并在我的设备上手动安装
这个问题已经有答案了: JS Simple but Safe Login? [closed] (1 个回答) 已关闭 6 年前。 我正在尝试使用 JavaScript 创建登录页面。它实际上只是一个带
其他章节请看: react 高效高质量搭建后台系统 系列 登录 本篇将完成 登录模块 。效果和 spug 相同: 需求 如下:
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 1 年前。
我在使用 ReactJs 中的 facebook-login 组件时遇到问题,代码与文档中的完全一样,但仍然无法正常工作。你能帮我找出我做错了什么吗? import React, { Componen
我有一个项目,其中包含许多具有自己的日志记录的“工具”类。这些日志文件是在应用程序启动时创建的,但在使用之前一直为空。 是否可以告诉logback在启动时不应该创建空文件?但是仅在使用它们时? 不知何
我正在创建一个需要用户授权才能访问某些功能的网站。我目前正在研究用户如何创建帐户以及如何利用 session 来授权他们的登录。用户信息存储在名为 user 的 MySQL 表中,其中可能包括用户名和
我是一名优秀的程序员,十分优秀!