I am using Angular 9 (localhost:4200) and WebAPI with dotnet Core 3.1 (localhost:5000). During user registration I pass user data from Client to Server and then in Register method I send him an email to verify. After user clicks the link it redirects him to localhost:5000 to VerifyEmail method.
How to create a link in Registration function so the code could hit the client function first and then confirm verification on server? Or there is better way to confirm email with Angular/dotnet core WebApi?
Client Side:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../_models/user';
import { environment } from '../../environments/environment';
@Injectable({
providedIn: 'root'
})
export class AuthService {
baseUrl = environment.apiUrl + 'auth/';
constructor(private http: HttpClient) {}
register(user: User) {
return this.http.post(this.baseUrl + 'register', user);
}
}
verifyEmail(data: any) { // not used
return this.http.post(this.baseUrl + 'VerifyEmail', data);
}
Server Side:
[HttpPost("register")]
public async Task<IActionResult> Register(UserForRegisterDto userForRegisterDto)
{
var code = string.Empty;
var userToCreate = _mapper.Map<User>(userForRegisterDto);
try
{
var userExists = await _userManager.FindByNameAsync(userToCreate.UserName);
if (userExists == null)
{
var result = await _userManager.CreateAsync(userToCreate, userForRegisterDto.Password);
code = await _userManager.GenerateEmailConfirmationTokenAsync(userToCreate);
if (result.Succeeded)
{
//some code
}
}
else
{
var emailConfirmed = await _userManager.IsEmailConfirmedAsync(userExists);
code = await _userManager.GenerateEmailConfirmationTokenAsync(userExists);
if (emailConfirmed)
{
return Ok();
}
}
var link = Url.Action(nameof(VerifyEmail), "Auth", new { userId = userToCreate.Id, code }, Request.Scheme, Request.Host.ToString());
await _emailService.SendAsync("test@test.com", "email verify", $"<a href=\"{link}\">Verify Email</a>", true);
}
catch (Exception ex)
{
throw;
}
return Ok();
}
public async Task<IActionResult> VerifyEmail(string userId, string code)
{
if (string.IsNullOrEmpty(userId) || string.IsNullOrEmpty(code))
{
return BadRequest();
}
var user = await _userManager.FindByIdAsync(userId);
if (user == null)
{
return BadRequest();
}
if (user.EmailConfirmed)
{
//return Ok();
}
var result = await _userManager.ConfirmEmailAsync(user, code);
if (result.Succeeded)
{
return Ok();
}
return BadRequest();
}
Thank you in advance for any help and your time!
I'd create a new angular component that resolves to /verify-email route and from there called AuthService
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'email-verification',
template: '<h1>{{status}}</h1>',
styleUrls: [ './email-verification.component.css' ]
})
export class EmailVerificationComponent implements OnInit {
status: string = "Verifying...";
constructor(private authService: AuthService){}
ngOnInit() {
this.authService.verifyEmail().subscribe(_ => this.status = "Email verified!");
//redirect to another component
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.