Click here to Skip to main content
15,868,016 members
Articles / Hosted Services / Azure

Code Example for SPA and Micro-Service on Azure

Rate me:
Please Sign up or sign in to vote.
5.00/5 (6 votes)
25 Mar 2020CPOL3 min read 14.5K   15   2
This is a demonstration of a basic example of single page Angular application and micro-service architecture on Azure.
The Angular application uses adal-angular4 to authenticate against Azure Active Directory users. This first version is for explaining the architecture and service integration part with some very basic functions: register user, activate account, keyin data and see simple report.

Background

SPA and micro-service is the trend for modern web application. Moreover, there is a high need of auto-scalability and well-supported Cloud environment. Last but not the least, that is a single sign-on ability and easy to integrate any Identity Provider. Azure Active Directory is an enterprise Identity Provider for both B2B and B2C solution.

Image 1

Using the Code

https://github.com/quinvit/microcore/tree/master/Sample/Angular

  1. time-tracker-ui folder contains sample code of Angular application
  2. TimeTrackerAPI folder contains sample code of API Gateway
  3. Services folder contains sample code of two simple microservices

The API Gateway and micro-services are deployed to Azure Web App (linux docker container mode) in order that we can easily scale up or scale out any service. On the other hand, hosting microservice in Azure Web App is much cheaper than on VM or AKS. To secure our microservices that are hosted under Azure web app, we need to use a Virtual Network with enabled Service Endpoint, join our Azure web app to that Virtual Network and then restrict all external access to the web app, except the requests that come from our Virtual Network.

Image 2

The communication between micro-services is asynchronous HTTP and is handled by https://github.com/quinvit/microcore library. The library covers network call, serialization/deserialization, contract mapping. We only use our micro-services by using DI to inject service interface to constructor as normal in-process service injection.

In Angular frontend, we simply use adal-angular4 library to authenticate against Azure Active Directory users and auto-attach jwt bearer token when we call any API using HttpClient.

C#
 @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<DailyTimeSheetByUser[]>
          (`${environment.config.apiGateway}/api/Reports/MonthlyReportByUser`)
      .subscribe(x => {
        this.dataSource = x;
      });
  }
}

For more details about this library, please take a look at this article.

To start Angular application, type ng serve:

Image 3

For the backend, register micro-services in Discovery.config:

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <Discovery>
    <Services>
      <ReportService Source="Config" Hosts="localhost:80" />
      <AuthService Source="Config" Hosts="localhost:81" />
      
      <!--<ReportService Source="Config" 
           Hosts="timetracker-reportservice.azurewebsites.net:80" />
      <AuthService Source="Config" 
       Hosts="timetracker-authservice.azurewebsites.net:80" />-->
    </Services>
  </Discovery>
</configuration>

This is how micro-services are integrated to ASP.NET Core (Startup.cs):

C#
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddTransient((o) => StandardKernel.Get<IReportService>());
    services.AddTransient((o) => StandardKernel.Get<IAuthService>());
}

Inject remote service to the backend API code in API Gateway:

C#
[Authorize]
[Route("api/[controller]")]
[ApiController]
public class ReportsController : ControllerBase
{
    private IReportService _reportService;

    public ReportsController(IReportService reportService)
    {
        _reportService = reportService;
    }

    // GET: api/Reports
    [HttpGet]
    [Route("MonthlyReportByUser")]
    public async Task<DailyTimeByUser[]> GetMonthlyReportByUser()
    {
        var token = await this.HttpContext.GetTokenAsync("access_token");
        return await _reportService.GetMonthlyReportByUserAsync(token);
    }
}

To start backend API Gateway and micro-services at local, just run these projects in Visual Studio 2019:

Image 4

Here is how it works:

Image 5

To run and store data locally, we need to run Azure Storage Emulator. Finally, after login to demo users, this is how the application looks like:

Image 6

Points of Interest

Online demo can be found at https://timetracker2.z7.web.core.windows.net/.

You can register or use sample users:

  • quinvit@hyperscale2.onmicrosoft.com/microcore@911

After login, click on Timesheet menu to retrieve data from server. Here is the data flow:

Angular application

  • API Gateway
    • ReportService (retrieve report data in Azure table)
      • AuthService (retrieve logged-in user information)
    • AuthService (add registration information to Azure table)
      • Push a message to Azure queue to trigger Azure login apps to create AD user and send email with initial password

The user registration information is pushed to Azure storage queue and there is an Azure logic app that will handle user creation and send email with initial password.

Image 7

History

This first version is for explaining the architecture and service integration part with some very basic functions: register user, activate account, keyin data and see simple report. In the next version, I will make more real-life features like data analysis and charting...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Vietnam Vietnam
Learning IT Technology since 2001, I get started with C++ from 2003. I switch to C# and.NET framework since 2004. Now I am a NodeJS / .NET Core programmer on Azure.

Comments and Discussions

 
QuestionQuestion about micro-service Pin
deamnguyen24-Sep-19 5:43
deamnguyen24-Sep-19 5:43 
AnswerRe: Question about micro-service Pin
Quí Nguyễn NT24-Sep-19 20:25
Quí Nguyễn NT24-Sep-19 20:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.