Skip to content
Article

Shared Google Authorization with an Angular site and .Net Core API.

There are many Angular tutorials for setting up websites using the Angular framework and .NET Core APIs. Likewise, there are many walkthroughs for integrating Google authentication with each. However, implementing these solutions separately yield the need to authenticate through Google twice, once for the angular site, once for the API.

This article provides a solution that allows shared Google authorization through authentication on the angular site. To surpass the need to authenticate a second time, pass the token through a standard header to the API and use Google libraries to validate and authorize.

Technology used in this Angular tutorial.

This post assumes you’ve got the basic angular website and Web API projects running. This post will also likely be effective for any angular site 2+ or front end site where google authentication occurs. It should also work if your Web API project is Core 2+.

The site I’m working with is designed to be exclusively authenticated through Google, however this method could be extended to handle multiple authentication formats (assuming there are .Net validation libraries for them or you write your own). Therefore, one other aspect to mention is that I am not storing any user data in a database.

Using the Angular site, Google login, and local storage as a start.

The primary goal is to make sure you have access to Google’s idToken after authentication. Using the angular-social-login default setup is pretty simple to get working. This is a pretty good article which also walks through setting up the Google App as part of this if you need. I can’t find the original post I followed, but this stackoverflow post shows storing the Google user/token in state for future calls.

This code block (customauth.service.ts in the Angular site) just shows that on user subscription the user is stored in local storage:

  constructor(
    public authService: AuthService,
    public router: Router,
    public ngZone: NgZone // NgZone service to remove outside scope warning
  ) {
    // Setting logged in user in localstorage else null
    this.authService.authState.subscribe(user => {
      if (user) {
        this.userData = user;
        localStorage.setItem('user', JSON.stringify(this.userData));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    });
  }

  // Sign in with Google
  GoogleAuth() {
    return this.authService.signIn(GoogleLoginProvider.PROVIDER_ID);
  }

  // Sign out
  SignOut() {
    return this.authService.signOut().then(() => {
      localStorage.removeItem('user');
      this.router.navigate(['/']);
    });
  }

Options researched before finding the current solution.

  • The Microsoft standard way to handle google authentication. This is slick if you’re building an MVC site and need to allow Google auth, but I couldn’t find a way to allow sending over the token, as this generates and uses a cookie value with a Identity.External key.
  • JWT authorization is an option, but the tutorials got heavy quickly. Since I don’t need to store users or use Microsoft Identity, I blew past this.
  • A custom policy provider is another Microsft standard practice. There might be a better way to accomplish the solution using this approach, but I didn’t walk this path too far since I wasn’t using authentication through the .Net solution.

The solution: a .Net Core custom authorize attribute.

I used this stackoverflow post about custom auth attributes to hook up the solution. This is what allows the shared Google authorization using a standard authorization request header.

Approach

  1. In Angular
    1. Build the Authorization header using the Google idToken.
    2. Pass the header for any authorize only API endpoints.
  2. In the web API
    1. Enable authorization
    2. Create a custom IAuthorizationFilter and TypeFilterAttribute
    3. Tag any controllers or endpoints with the custom attribute

I provide code samples for these steps below.

Angular API calls with an authorization header.

The code in the api service (api.service.ts in Angular Site) grabs the id token from the user in local storage and passes it through the API call. If the user is logged out, this header isn’t passed.

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { SocialUser } from 'angularx-social-login';
import { environment } from './../../environments/environment';

export class ApiService {
  apiURL = environment.apiUrl;
  user: SocialUser;
  defaultHeaders: HttpHeaders;

  constructor(private httpClient: HttpClient) {
    this.user = JSON.parse(localStorage.getItem('user'));
    this.defaultHeaders = new HttpHeaders();
    this.defaultHeaders = this.defaultHeaders.append('Content-Type', 'application/json');
    if (this.user != null) {
      this.defaultHeaders = this.defaultHeaders.append('Authorization', 'Bearer ' + this.user.idToken);
    }
  }

  public getAccounts() {
    const accounts = this.httpClient.get<Account[]>(`${this.apiURL}/accounts`, { headers: this.defaultHeaders });
    return accounts;
  }
}

Enabling authorization in the .Net Core project.

In the StartUp file (StartUp.cs in the API project), authorization has to be enabled.

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
  ...
  app.UseRouting();
  app.UseAuthorization();
  app.UseEndpoints(endpoints =>
  {
      endpoints.MapControllers();
  });
}

The custom filter attribute to validate without another authorization.

This creates the attribute used for authorization and performs a Google validation on the token.

This application is used only for our Google G Suite users, and thus the “HostedDomain” option of the ValidationSettings is set. This isn’t necessary, and I believe can just be removed if you allow any Google user to authenticate.

I’ve named this file GoogleAuthorizationFilter.cs in the API project.

using Google.Apis.Auth;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;

namespace YourNamespace.API.Attributes
{
    /// <summary>
    /// Custom Google Authentication authorize attribute which validates the bearer token.
    /// </summary>
    public class GoogleAuthorizeAttribute : TypeFilterAttribute
    {
        public GoogleAuthorizeAttribute() : base(typeof(GoogleAuthorizeFilter)) { }
    }


    public class GoogleAuthorizeFilter : IAuthorizationFilter
    {

        public GoogleAuthorizeFilter()
        {
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            try
            {
                // Verify Authorization header exists
                var headers = context.HttpContext.Request.Headers;
                if (!headers.ContainsKey("Authorization"))
                {
                    context.Result = new ForbidResult();
                }
                var authHeader = headers["Authorization"].ToString();

                // Verify authorization header starts with bearer and has a token
                if (!authHeader.StartsWith("Bearer ") && authHeader.Length > 7)
                {
                    context.Result = new ForbidResult();
                }

                // Grab the token and verify through google. If verification fails, and exception will be thrown.
                var token = authHeader.Remove(0, 7);
                var validated = GoogleJsonWebSignature.ValidateAsync(token, new GoogleJsonWebSignature.ValidationSettings()
                {
                    HostedDomain = "yourdomain.com",
                }).Result;
            }
            catch (Exception)
            {
                context.Result = new ForbidResult();
            }
        }
    }
}

Putting the custom attribute in place.

This is just a snippet of code, as on your controllers you just have to add the one line of code (well, two including the using statement). If the GoogleAuthorize doesn’t validate, the call returns as access denied.

using YourNamespace.API.Attributes;

[GoogleAuthorize]
[ApiController]
public class AccountsController : BaseController {

Voila! No need for a second authentication.

The .Net API is now locked down only to requests originating from a site with Google authentication. The custom attribute can be extended for additional authentication sources or any other desired restrictions using the request. I like the simplicity of a site which allows Google auth only, but it wouldn’t be a stretch to add others – and I really like not managing any users or passwords. I hope this Angular tutorial for shared Google authentication works well for you too!

The Atlantic BT Manifesto

The Ultimate Guide To Planning A Complex Web Project

Insights

Atlantic BT's Insights

We’re sharing the latest concepts in tech, design, and software development. Learn more about our findings.

Questions & Answers

Can you integrate with my existing systems and teams?

Yes, both technically and operationally. On the technical side, our engineering heritage allows us to connect modern cloud, data, and AI capabilities securely to your existing ERPs, CRMs, and proprietary software using SOC 2 Type 2 certified practices. On the operational side, we never work in a silo. Our senior architects embed directly with your in-house developers and stakeholders, aligning with your governance protocols and building internal capability so your team can confidently maintain and scale the system.

Learn More about Can you integrate with my existing systems and teams?
Why should we pay for a discovery phase when we can jump straight into development?

Investing in a strategy and discovery phase prevents costly rework, scope creep, and misaligned features before your engineering budget is committed to full-scale development. While jumping straight into writing code can feel faster at the beginning, uncovering hidden legacy bottlenecks, unclear user requirements, or integration roadblocks midway through a build is significantly more expensive to fix in production than on paper.

A structured discovery phase protects your budget and timeline in four practical ways:

  • Validates Assumptions Before Engineering Begins: Through stakeholder interviews, workflow observations, and a clickable prototype, your team can test user flows and gather real feedback early so we can ensure we build the exact features your business needs.
  • Uncovers Hidden Technical Constraints: Auditing your existing databases, APIs, and security requirements upfront reveals integration hurdles and technical debt before developers write a single line of production code.
  • Produces Accurate Budgets & Timelines: Defining clear technical requirements and architecture blueprints eliminates guesswork, giving leadership reliable cost estimates and realistic delivery milestones.
  • Aligns Leadership & Technical Teams: Getting executive sponsors, end users, and IT stakeholders on the same page early prevents mid-project priority shifts that stall momentum and inflate costs.

Learn More about Why should we pay for a discovery phase when we can jump straight into development?
What does my business get by the end of a technology consulting engagement?

At the end of a technology consulting engagement with Atlantic BT, your business walks away with a clear, actionable blueprint and a validated prototype so your leadership team can move into development with full confidence. Rather than leaving you with high-level theory, our senior architects deliver concrete artifacts built around your actual operations:

  • Stakeholder & Workflow Findings: Insights gathered from executive stakeholder interviews and hands-on contextual inquiries that map out how your teams currently work and where daily bottlenecks occur.
  • Comprehensive Systems Audit: A technical evaluation of your existing software stack, databases, integrations, and security posture to pinpoint technical debt and modernization opportunities.
  • Prioritized Recommendations & Roadmap: An objective, vendor-agnostic plan outlining which software, cloud, or AI solutions will deliver the highest return on investment, complete with scope, timeline, and budget estimates.
  • Fully Clickable Prototype: If building software, an interactive front-end prototype that lets your team test user flows, validate assumptions, and gather real feedback before investing in full-scale engineering.

Learn More about What does my business get by the end of a technology consulting engagement?
What does enterprise technology consulting cost for businesses?

A focused enterprise AI readiness assessment and strategy roadmap typically ranges from $10,000 to $75,000, depending on the complexity of your data infrastructure, security requirements, and the number of workflows evaluated. At Atlantic BT, we scope engagements transparently around defined deliverables, such as a systems audit, prioritized ROI roadmap, and working prototype, so you can validate business value before committing to full-scale development. 

Our initial AI strategy discovery process starts at $10,000 and includes evaluation of 3 workflows and initial suggestions.

Learn More about What does enterprise technology consulting cost for businesses?
How much does a custom web application cost?

The investment for a custom web application typically ranges from $50,000 to $200,000+, depending on the complexity of the feature set, the number of user roles, the depth of data integrations, and specific security compliance requirements.

We categorize development into three strategic engineering tiers:

  • Minimum Viable Product / Core Web App ($50,000 – $80,000): Ideal for launching a first-generation custom tool or migrating a single manual workflow online. This includes a fully custom UI/UX design, a relational database setup, standard secure user authentication (login/signup), and core functional features for 1–2 distinct user roles (e.g., client vs. administrator).
  • Advanced Scale & Client Portals ($80,000 – $150,000): Built for mid-market and enterprise companies looking to centralize operations. This tier covers complex, multi-tenant architectures (portals with unique user views), custom API layers to sync data with external CRMs or ERPs, advanced search/filtering, automated PDF/report generation, and interactive data dashboards.
  • Enterprise Application Ecosystem ($150,000+): Mission-critical software built for global organizations. This includes heavy legacy system synchronization, architecture for infinite scalability, data pipelines, machine learning or AI integration, and rigid compliance standards (SOC 2, HIPAA, or ISO 27001).

Learn More about How much does a custom web application cost?
Do you provide ongoing support after the launch?

Yes! Our custom web application maintenance includes a range of critical services: from regular updates and security patches to adding new features and strategic planning. These continuous efforts ensure that a website remains secure, efficient, and aligned with your business’s goals.

Learn More about Do you provide ongoing support after the launch?
How do custom web applications support business growth?

Custom web applications (such as client portals, dashboards or workflow automation tools) support business growth by improving client retention, lower operational overhead and bottle necks, and build scalable property for your organization. 

  • Enhancing the Customer Experience: A custom app provides your customers with a tailored self-service environment, which allows them to complete their tasks quickly and efficiently. 
  • Consolidating Fragmented Business Tools: As businesses grow, they often end up with several disjointed applications. We develop custom web applications that centralize these disparate functions through a cohesive interface. 
  • Software That Grows with your Business: With the ongoing support that we provide after the initial build, we include updates that keep your custom web application ahead of technical debt.

Learn More about How do custom web applications support business growth?