在当今的软件开发领域,微服务架构因其灵活性和可扩展性而受到青睐。随着云计算技术的发展,云平台为微服务提供了理想的运行环境。本文将探讨如何在云环境中构建微服务架构,并使用AzureActive Directory进行身份验证。
在构建微服务架构时,需要考虑以下几个关键需求:
Azure Active Directory是一个企业级的身份提供者,适用于B2B和B2C解决方案。
API网关和微服务部署在Azure Web App上,以便于轻松地进行水平或垂直扩展。与虚拟机或AKS相比,使用Azure Web App托管微服务成本更低。
为了保护托管在Azure Web App下的微服务,需要使用启用了服务端点的虚拟网络,将Azure Web App加入到该虚拟网络,并限制所有外部访问,只允许来自虚拟网络的请求。
微服务之间的通信是异步的HTTP通信,由处理。该库涵盖了网络调用、序列化/反序列化、契约映射等功能。通过依赖注入(DI)将服务接口注入到构造函数中,就像在进程内服务注入一样使用微服务。
在Angular前端,使用adal-angular4库对Azure Active Directory用户进行身份验证,并在调用任何API时自动附加JWT承载令牌。
@Component({
  selector: 'app-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.css']
})
export class ReportsComponent implements OnInit {
  displayedColumns: string[] = ['tasks', 'totalMinutes', 'day'];
  dataSource = ELEMENT_DATA;
  constructor(private http: HttpClient) { }
  ngOnInit() {
    this.http.get(`${environment.config.apiGateway}/api/Reports/MonthlyReportByUser`)
      .subscribe(x => {
        this.dataSource = x;
      });
  }
}
     
要启动Angular应用,请在命令行中输入:
ng serve
在Discovery.config中注册微服务:
 
 
 
在ASP.NET Core的Startup.cs中集成微服务:
public void ConfigureServices(IServiceCollection services) {
    ...
    services.AddTransient((o) => StandardKernel.Get());
    services.AddTransient((o) => StandardKernel.Get());
}
      
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ReportsController : ControllerBase {
    private IReportService _reportService;
    public ReportsController(IReportService reportService) {
        _reportService = reportService;
    }
    [HttpGet]
    [Route("MonthlyReportByUser")]
    public async Task GetMonthlyReportByUser() {
        var token = await this.HttpContext.GetTokenAsync("access_token");
        return await _reportService.GetMonthlyReportByUserAsync(token);
    }
}
     
在Visual Studio 2019中运行这些项目即可启动后端API网关和微服务。
登录演示用户后,点击“Timesheet”菜单即可从服务器检索数据。数据流如下:
用户注册信息被推送到Azure存储队列,有一个Azure逻辑应用将处理用户创建并发送带有初始密码的电子邮件。