步骤
1、Program.cs
添加如下代码
builder.Services.AddTransient<IJwtService, JwtService>();
2、AccountController.cs
注册IJwtService
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly RoleManager<ApplicationRole> _roleManager;
private readonly IJwtService _jwtService;
/// <summary>
///
/// </summary>
/// <param name="userManager"></param>
/// <param name="signInManager"></param>
/// <param name="roleManager"></param>
public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, RoleManager<ApplicationRole> roleManager, IJwtService jwtService)
{
_userManager = userManager;
_signInManager = signInManager;
_roleManager = roleManager;
_jwtService = jwtService;
}
更新PostRegister方法中登录成功后的代码,返回user改为返回authenticationResponse
if (identityResult.Succeeded)
{
await _signInManager.SignInAsync(user, false);
AuthenticationResponse authenticationResponse = _jwtService.CreateJwtToken(user);
return Ok(authenticationResponse);
}
更新PostLogin方法
if (signInResult.Succeeded)
{
ApplicationUser? user = await _userManager.FindByEmailAsync(loginDTO.Email);
if (user == null)
{
return NoContent();
}
else
{
await _signInManager.SignInAsync(user, false);
AuthenticationResponse authenticationResponse = _jwtService.CreateJwtToken(user);
return Ok(authenticationResponse);
}
}
3、login.component.ts
添加localStorage["token"]
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { LoginUser } from '../models/login-user';
import { AccountService } from '../services/account.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
loginForm: FormGroup;
isLoginFormSubmitted: boolean = false;
constructor(private accountService: AccountService, private router: Router) {
this.loginForm = new FormGroup({
email: new FormControl(null, [Validators.required, Validators.email]),
password: new FormControl(null, [Validators.required]),
});
}
get login_emailControl(): any {
return this.loginForm.controls["email"];
}
get login_passwordControl(): any {
return this.loginForm.controls["password"];
}
loginSubmitted() {
this.isLoginFormSubmitted = true;
if (this.loginForm.valid) {
this.accountService.postLogin(this.loginForm.value).subscribe({
next: (response: any) => {
console.log(response);
this.isLoginFormSubmitted = false;
this.accountService.currentUserName = response.email;
localStorage["token"] = response.token;
this.router.navigate(['/cities']);
this.loginForm.reset();
},
error: (error: any) => {
console.log(error);
},
complete: () => { },
});
}
}
}
4、account.service.ts
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { LoginUser } from '../models/login-user';
import { RegisterUser } from '../models/register-user';
const API_BASE_URL: string = "https://localhost:7173/api/v1/account/";
@Injectable({
providedIn: 'root'
})
export class AccountService {
public currentUserName: string | null = null;
constructor(private httpClient: HttpClient) {
}
public postRegister(registerUser: RegisterUser): Observable<any> {
return this.httpClient.post<RegisterUser>(`${API_BASE_URL}register`, registerUser);
}
public postLogin(loginUser: LoginUser): Observable<any> {
return this.httpClient.post<any>(`${API_BASE_URL}login`, loginUser);
}
public getLogout(): Observable<string> {
return this.httpClient.get<string>(`${API_BASE_URL}logout`);
}
}
5、register.component.ts
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { RegisterUser } from '../models/register-user';
import { AccountService } from '../services/account.service';
import { CompareValidation } from '../validators/custom-validators';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent {
registerForm: FormGroup;
isRegisterFormSubmitted: boolean = false;
constructor(private accountService: AccountService, private router: Router) {
this.registerForm = new FormGroup({
personName: new FormControl(null, [Validators.required]),
email: new FormControl(null, [Validators.required]),
phoneNumber: new FormControl(null, [Validators.required]),
password: new FormControl(null, [Validators.required]),
confirmPassword: new FormControl(null, [Validators.required])
},
{
validators: [CompareValidation("password", "confirmPassword")]
});
}
get register_personNameControl(): any {
return this.registerForm.controls["personName"];
}
get register_emailControl(): any {
return this.registerForm.controls["email"];
}
get register_phoneNumberControl(): any {
return this.registerForm.controls["phoneNumber"];
}
get register_passwordControl(): any {
return this.registerForm.controls["password"];
}
get register_confirmPasswordControl(): any {
return this.registerForm.controls["confirmPassword"];
}
registerSubmitted() {
this.isRegisterFormSubmitted = true;
if (this.registerForm.valid) {
this.accountService.postRegister(this.registerForm.value).subscribe({
next: (response: any) => {
console.log(response);
this.isRegisterFormSubmitted = false;
localStorage["token"] = response.token;
this.router.navigate(['/cities']);
this.registerForm.reset();
},
error: (error) => {
console.log(error);
},
complete: () => { },
});
}
}
}
Gitee获取源码: