要实现Angular 8和Microsoft登录身份用户,可以使用Angular的HttpClient模块与Identity Server进行通信,并结合dotnet Core 3.0或3.1的身份验证机制。
首先,确保你已经安装了dotnet Core 3.0或3.1以及Angular 8。
步骤1:创建dotnet Core API项目 在命令行中执行以下命令,创建一个空的dotnet Core API项目:
dotnet new webapi -n MyApi
步骤2:添加Identity Server包 进入项目目录,并执行以下命令,添加Identity Server包:
cd MyApi
dotnet add package IdentityServer4
步骤3:配置Identity Server 在Startup.cs文件中,添加以下代码:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using IdentityServer4.Models;
using IdentityServer4.Test;
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
// 添加Identity Server
services.AddIdentityServer()
.AddInMemoryClients(new Client[]
{
new Client
{
ClientId = "angular-app",
AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "api" }
}
})
.AddInMemoryApiResources(new ApiResource[]
{
new ApiResource("api", "My API")
})
.AddTestUsers(new TestUser[]
{
new TestUser
{
SubjectId = "1",
Username = "admin",
Password = "password"
}
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseIdentityServer();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
步骤4:创建API控制器 在Controllers文件夹下,创建一个新的控制器文件(例如,ValuesController.cs),并添加以下代码:
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[Authorize]
[ApiController]
[Route("api/[controller]")]
public class ValuesController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
return Ok(new string[] { "value1", "value2" });
}
}
步骤5:启动API项目 在命令行中执行以下命令,启动API项目:
dotnet run
API项目将在https://localhost:5001或http://localhost:5000上运行。
步骤6:创建Angular项目 在命令行中执行以下命令,创建一个新的Angular项目:
ng new MyAngularApp
步骤7:添加Angular HttpClient模块 进入项目目录,并执行以下命令,添加HttpClient模块:
cd MyAngularApp
npm install @angular/common@8.2.14 @angular/core@8.2.14 @angular/forms@8.2.14 @angular/platform-browser@8.2.14 @angular/platform-browser-dynamic@8.2.14 rxjs@6.5.4
步骤8:修改app.module.ts 打开src/app/app.module.ts文件,并添加以下代码:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
步骤9:创建登录组件 在src/app文件夹下,创建一个新的组件文件(例如,login.component.ts),并添加以下代码:
import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-login',
template: `
Login
相关内容