简体   繁体   English

Angular 8 和 Microsoft 登录身份用户 (dotnet Core 3.0 3.1)

[英]Angular 8 and Microsoft Login Identity User (dotnet Core 3.0 3.1)

Please bear with me since I am new to Angular and Identity User login process.请耐心等待,因为我是 Angular 和 Identity User 登录过程的新手。

I have an Angular project with authentication user (login/logout, register and profile, etc.).我有一个带有身份验证用户(登录/注销、注册和配置文件等)的 Angular 项目。 The back end is an MSFT database backend to support these features.后端是支持这些功能的 MSFT 数据库后端。

I am able to add additional information to the registration process (LastName, FirstName, Gender, etc.).我可以在注册过程中添加其他信息(姓氏、名字、性别等)。

Here is my problem: My Angular component or pages can not see the information this MSFT process.这是我的问题:我的 Angular 组件或页面无法看到此 MSFT 进程的信息。 I have seen a process "private async Task LoadAsync(ApplicationUser user)" for example in the code but I don't know how initiate to call from Angular side (I believe it something like http://localhost:4200/area/Identity/page/account/manage ... Can it be done or I am way off the reality?例如,我在代码中看到了一个进程“private async Task LoadAsync(ApplicationUser user)”,但我不知道如何从 Angular 端发起调用(我相信它类似于http://localhost:4200/area/Identity /page/account/manage ... 可以完成还是我离现实很远?

Please direct me to the right direction or a sample of code will be appreciated very much.请指导我正确的方向或代码示例将不胜感激。

the code below is from ..\\Areas\\Identity\\Pages\\Account\\Manage\\index.cshtml.cs下面的代码来自 ..\\Areas\\Identity\\Pages\\Account\\Manage\\index.cshtml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using WebAngular.Models;

namespace WebAngular.Areas.Identity.Pages.Account.Manage
{
    public partial class IndexModel : PageModel
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;

        public IndexModel(
            UserManager<ApplicationUser> userManager,
            SignInManager<ApplicationUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }

        public string Username { get; set; }

        [TempData]
        public string StatusMessage { get; set; }

        [BindProperty]
        public InputModel Input { get; set; }

        public class InputModel
        {
            [Phone]
            [Display(Name = "Phone number")]
            public string PhoneNumber { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string MiddleName { get; set; }
            public string Gender { get; set; }
            public string AboutUser { get; set; }
            public DateTime BirthDate { get; set; }

        }

        private async Task LoadAsync(ApplicationUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);
            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber,
                LastName = user.LastName,
                FirstName = user.FirstName,
                Gender = user.Gender,
                AboutUser = user.AboutUser,
                BirthDate = user.BirthDate,
                MiddleName = user.MiddleName,
            };
        }

        public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            await LoadAsync(user);
            return Page();
        }

        public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!ModelState.IsValid)
            {
                await LoadAsync(user);
                return Page();
            }

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);
            if (Input.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, Input.PhoneNumber);
                if (!setPhoneResult.Succeeded)
                {
                    var userId = await _userManager.GetUserIdAsync(user);
                    throw new InvalidOperationException($"Unexpected error occurred setting phone number for user with ID '{userId}'.");
                }
            }

            if (Input.BirthDate != user.BirthDate)
            {
                user.BirthDate = Input.BirthDate;
            }
            if (Input.FirstName != user.FirstName)
            {
                user.FirstName = Input.FirstName;
            }
            if (Input.LastName != user.LastName)
            {
                user.LastName = Input.LastName;
            }
            if (Input.AboutUser != user.AboutUser)
            {
                user.AboutUser = Input.AboutUser;
            }
            if (Input.Gender != user.Gender)
            {
                user.Gender = Input.Gender;
            }
            if (Input.MiddleName != user.MiddleName)
            {
                user.MiddleName = Input.MiddleName;
            }

            await _userManager.UpdateAsync(user);

            await _signInManager.RefreshSignInAsync(user);
            StatusMessage = "Your profile has been updated";
            return RedirectToPage();
        }
    }
}

I can display 'username' from the angular application.我可以从 angular 应用程序中显示“用户名”。

import { Component, OnInit } from '@angular/core';
import { ConfigService, AppConfig } from '../services/config/config.service';
import { AuthorizeService } from '../../api-authorization/authorize.service';
import { Observable } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
})
export class HomeComponent implements OnInit  {
  public isAuthenticated: Observable<boolean>;
  public userName: Observable<string>;
  public firstName: Observable<string>;
  appConfig: AppConfig;
  constructor(private appConfigProvider: ConfigService, private authorizeService: AuthorizeService) {
    appConfigProvider.loadConfig()
      .toPromise()
      .then(x => {
        this.appConfig = x;
      }
      );
    console.log(this.appConfig);
  }
  ngOnInit() {
    this.isAuthenticated = this.authorizeService.isAuthenticated();
    this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
  }

}

Basically, there are API in the api-authorization directory which allows me call via javascript/typescript.基本上,api-authorization 目录中有允许我通过 javascript/typescript 调用的 API。 However, I still not be able to display firstname, lastname etc. Can any one direct me to the right place (how to get user profile from angular)?但是,我仍然无法显示名字、姓氏等。任何人都可以将我引导到正确的位置(如何从 angular 获取用户个人资料)? Thanks.谢谢。

It is hell for me to go thru login.html, login.csthml in areas, src/api-authorization in ClientApp.在区域中通过 login.html、login.csthml、在 ClientApp 中通过 src/api-authorization 对我来说是地狱。

Instead I have created a controller to pull data from sql server.相反,我创建了一个控制器来从 sql server 中提取数据。 It not to bad, it is used userManage object to pull data from.还不错,它使用 userManage 对象从中提取数据。 here is my code to do it (just in case someone tries to do it just like me).这是我的代码(以防万一有人像我一样尝试这样做)。

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using WebAngular.Models;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;


namespace WebAngular.Controllers
{
    [ApiController]
    [Route("getUserProfileAsync")]
    public class UserProfileController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;
        public UserProfileController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpGet]
        [Authorize]
        public async Task<object> Get()
        {
            string userId = User.FindFirstValue(ClaimTypes.NameIdentifier);
            var user = await _userManager.FindByIdAsync(userId);
            var fullName = user.FirstName + ' ' + user.LastName;

            return Ok(new
            {
                user.Id,
                user.PhoneNumber,
                user.LastName,
                user.FirstName,
                user.MiddleName,
                user.Gender,
                user.AboutUser,
                user.BirthDate,
                fullName

            });
        }
    }

}

here are the codes in my Angular services这是我的 Angular 服务中的代码

private profileUrl: string;
  constructor(private http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    this.configUrl = baseUrl + 'config';
    this.profileUrl = baseUrl + 'getUserProfileAsync';
  }

and the method/function to get user profile:以及获取用户个人资料的方法/功能:

 getUserProfile(): Observable<any> {
    return this.http.get<any>(this.profileUrl)
      .pipe(
        tap(() => console.log("HTTP request executed")),
        catchError(err => {
          console.log('Handling error locally and rethrowing it...', err);
          return throwError(err);
        }),
        finalize(() => console.log("second finalize() block executed"))
      );
  }

and the last piece... you need to put it in a component where you want to see the user profile最后一块......你需要把它放在一个你想查看用户配置文件的组件中

ngOnInit() {
    this.isAuthenticated = this.authorizeService.isAuthenticated();
    if (this.isAuthenticated) {
      this.appConfigProvider.getUserProfile()
        .toPromise()
        .then(x => {
          this.profile = x;
        }
        );

    }
  }

and in the component template (html):并在组件模板 (html) 中:

<pre>
{{ profile | json  }}
</pre>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Dotnet core 3.1 和 Angular 9 的 AAD 注册 - AAD registration for Dotnet core 3.1 and Angular 9 如何为我的 React/.NET Core 3.0 SPA web 应用程序添加 Microsoft Identity/Azure AD 登录功能 - How to add Microsoft Identity/Azure AD login feature for my React/.NET Core 3.0 SPA web application 登录成功后传递用户详细信息来自身份asp.net core 3.1 - Pass user detail after Login Is successful From identity asp.net core 3.1 在 .Net Core 3.1 身份中具有角色的用户列表 - User List with Role in .Net Core 3.1 Identity 带有 Identity Core 和 Asp.net Core 3.1 的多重登录页面 - Multiple Login Page with Identity Core and Asp.net Core 3.1 dotnet核心授权始终重定向到身份默认登录页面 - dotnet core authorize always redirect to identity default login page dotnet core 3.1 授权 Cognito 用户组声明问题 - dotnet core 3.1 Authorization Cognito user groups claims issue .NET Core 3.1 身份登录 Azure 需要很长时间 - .NET Core 3.1 Identity takes too long to login on Azure 在 ASP.net core 3.0 中更改身份登录 URL - Change identity login URL in ASP.net core 3.0 种子 ASP.NET .NET Core 3.1 中的身份用户和角色 - Seed ASP.NET Identity user and roles in .NET Core 3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM