337 Generating JWT Tokens 02(使用)

步骤

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获取源码:

https://gitee.com/huang_jianhua0101/asp.-net-core-8.git

  • 15
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黄健华Yeah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值