CategorySoftware Architecture

Handling Authentication and Authorization in Microservices – Part 2

In the previous post we saw a way for handling authentication using an API Gateway and an Identity Provider. Just to refresh the concept, here’s the basic diagram:

The Client will call the API Gateway, which will ask the Identity Provider to (ehm) provide the user details. The Client will get redirected to an external area where the user can login. At this point the Provider will generate a token and pass it back to the Client, which will then attach it to every call to the API Gateway.

So now that we have our user, we need a way to check his permissions in every microservice.

An option could be using Claims-based authorization , which basically means storing every permission that the user has on the entire system as claims on the token.

When a microservice receives a request, it will decode the token, verify it and then check if the user has the required permission claim for the requested action.

It’s a very easy mechanism to implement and works pretty well but also means that we’re sending back and forth a “fat” token, bloated with a lot of useless information for most of the calls. The permission claims are an interesting information only for the microservice that cover that specific bounded context. All the other will still receive the data but it won’t add any value.

Another option is to add an Authorization microservice, something like this:

Authorization Service
Authorization Service

This new microservice will basically own all the permissions for every user in the system.

When a microservice receives a request, it will decode the token and verify it. So far so good. Then, if the action requires authorization, it will make a call to the Authorization service, asking if the user has a specific permission.

This way we have decoupled the decision from the microservices, moving it to a specific service that does a single job: handling user permissions (and probably stuff like profiles/roles too ).

Handling Authentication and Authorization in Microservices – Part 1

In the last few weeks I’ve started working mainly on a quite important part of the system: adding authentication and authorization to some of the microservices that compose the whole application.

For those who don’t know, I work for a quite well know Company on the internal sales tools. In a nutshell we could say that is an enormous e-commerce, but of course there’s more on the plate than that.

But let’s go back to the topic. As I was saying, I’ve been tasked to add authentication and authorization to a bunch of microservices. Of course we were already checking the user identity before. And yes, we care a lot about who can do what. But we are constantly pushing to do more and more and add functionalities on top of the others, so one nice day we got from the architects a whole lot of new requirements to implement.

And so the fun had begun.

In this post I won’t go of course into the details of the actual implementation, however I’ll share with you one of the strategies that can be applied to solve this kind of task.

First of all, for those of you who still don’t know, authentication is the process of identifying who the user actually is. Hopefully, if the credentials are correct, this will generate some kind of user object containing few useful details (eg: name, email and so on).

Box for Guess Who, courtesy of geekyhobbies.com

Authorization instead means figuring out what the user can do on the system. Can he read data? Can he create contents? I guess you got the point.

In the microservice world authorization can be handled more granularly if the bounded contexts are defined properly.

Now that the basics are covered, let’s try to move on to the juicy part! Normally, when talking about microservices, one of the most common architectural design patterns is the API Gateway :

API Gateway

The idea here is to have a layer in the middle between the client and the actual microservices. This Gateway can build and prepare the DTOs based on the client type (eg: a mobile might see less data than a desktop), do logging, caching, and handle authentication as well. There are of course many more things it could do but that’s a topic for another post.

So how this gateway can help us? We need to introduce another block: the Identity Provider.

API Gateway and Identity Provider

Here’s the flow: the Gateway will call the Identity Provider, possibly redirecting the user to a “safe zone” where he/she can enter the credentials and get redirected back to our application, this time with a nice token containing the user details.

There are several types of token we can use, cool kids these days are using JWT. Quoting the docs:

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. 

Pretty neat, isn’t it?

Now we got our user authenticated in the Gateway, but we still need to handle authorization at the microservice level. We’ll see how in the next post of this series!

Using Decorators to handle cross-cutting concerns — Part 2 : a practical example

In my previous article I discussed a bit about how to use the Decorator pattern to implement cross-cutting concerns and reduce clutter in your codebase.

Today it’s going to be a bit more practical: we’ll be looking at a small demo I published on Github that makes use of Decorators as well as some other interesting things like .NET Attributes, CQRS and Dependency Injection.

I’m not going to deep dive into the details of CQRS as it would obviously take too much time and it’s outside the scope of this article. I’m using it here because query/command handlers usually expose just one method so there is no need to implement a big interface. Also, I like the pattern a lot 🙂

So let’s go straight to the code! The repository is available here: https://github.com/mizrael/cross-cutting-concern-attributes

It’s a very small .NET Core WebAPI application, nothing particularly fancy. No infrastructure of course, there’s no need for this article.

There’s just one API controller, exposing a single GET endpoint to retrieve a list of “values”. I might have called it “stuff” instead of “values”, it’s just an excuse to retrieve some data from the backend.

As you may have noticed, there’s no direct reference to the query handler in the API controller: I prefer to use MediatR to avoid injecting too many things in the constructor. It has become an habit so I’m doing it even when there’s just one dependency.

For those who don’t know it, MediatR acts as a simple in-process message bus, allowing quick dispatch of commands, queries and events. So, basically, it’s a very handy tool when implementing CQRS.

The ValuesArchiveHandler class handles the actual execution of the query. Actually it’s not doing much, apart from returning a fixed list of strings.

What we’re interested into actually is that small attribute, [Instrumentation] . It is just a marker, the real grunt-work will be elsewhere. I could have used an interface as well of course, but there are several reasons why I didn’t.

First of all, I prefer to avoid empty interfaces: an interface is a contract, and an interface without method doesn’t define any contract.

Moreover, attributes can always be configured to not propagate to descendant types automatically, something you cannot do with interfaces.

Now, take a look at the InstrumentationQueryHandlerDecorator class. It’s a query handler Decorator, so it gets an instance of a query handler injected in the constructor, and uses it in the Handle() method.

This decorator is not doing anything particular fancy, it’s just using Stopwatch to track how much time the inner handler is taking to complete.

What we’re interested into is the constructor: there the system is checking if the inner instance has been marked with the [Instrumentation] attribute, flipping a boolean value based on the result. That bool will then be used in the Handle() method to turn the instrumentation on or off. That’s it!

I’m using StructureMap as my IoC container and I’m taking care of the handler registration here . In the same file I also decorate all the query handlers with the InstrumentationQueryHandlerDecorator .

Keep in mind that I could have added some smarts here and check at registration time if a particular handler had been decorated with the [Instrumentation] attribute.

That would probably be a better solution as it would avoid runtime type checks, handling everything during the application bootstrap.

I’ll probably add this to the repository, I left it out to keep things simple 🙂

This article is also available on Medium as part of a series:

Using Decorators to handle cross-cutting concerns

I was actually planning of posting this article here but I was migrating to another server the last week and it took one week for the domain to point to the new DNS. Turns out this gave me the chance to try Medium instead, so published my first article there.

This time I’ll be writing about a very simple but powerful technique to reduce boiler-plate caused by cross-cutting concerns. In this post we’ll explore a simple way to encapsulate them in reusable components using the Decorator pattern.

Let’s first talk a bit about “cross cutting concerns”. On Wikipedia we can find this definition:

Cross-cutting concerns are parts of a program that rely on or must affect many other parts of the system.

In a nutshell, they represent almost everything not completely tied to the domain of the application but that can affect in some way the behaviour of its components.

Examples can be:
– caching
– error handling
– logging
– instrumentation

Instrumentation for instance can lead to a lot of boilerplate code which eventually will create clutter and pollute your codebase. You’ll basically end up with a lot of code like this:

Of course, being IT professionals, you can quickly come up with a decent solution, find the common denominator, extract the functionality, refactor and so on.

So…how would you do it? One option would be to use the Decorator pattern! It’s a very common pattern and quite easy to understand:

Basically you have a Foo class that you need somewhere that implements a well known interface, and you need to wrap it into some cross-cutting concern. All you have to do is:

  1. create a new container class implementing the same interface
  2. inject the “real” instance
  3. write your new logic where you need
  4. call the method on the inner instance
  5. sit back and enjoy!

Very handy. Of course it can be quite awkward in case your interface has a lot of methods, but in that case you might have to reconsider your architecture as it is probably breaking SRP.

One option would be moving to CQSCQRS. In the next post of the series we will see a practical example and discuss why those patterns can be an even more interesting option when combined with Decorators.

Stay tuned!

The importance of setting the boundaries (of your domain models)

First article of the year! I really wanted to start writing this few weeks ago, but honestly I wasn’t inspired enough.
Now that I’ve spent a good portion of the Christmas break reading blogs, books and watching courses on Pluralsight, I still don’t feel inspired enough.

I guess it’s due to how I spent the other portion (eating, sleeping and playing with my kids, mostly), which left me basically without any energy at all.

But as they say, the first step is always the hardest, no?

Lately I’ve been putting some effort into improving my DDD techniques. For those of you who are still living under a rock, please consider taking a copy of the marvelous blue book by Eric Evans.

I still am in the middle of the learning process, even though I probably started this path years ago. Might be a sign of impostorism. Or it might be the fact that in this job, as in many other jobs, you never stop learning.

Not going to discuss about DDD now, or what the benefits are. I shall leave this for another post.

This is going to be just a very quick introduction about boundaries and aggregates instead. What’s an aggregate? An example should make things easier.

We can consider an Order our aggregate and Order Lines compose its internal state.

I said “internal” for a reason: the Order is the “entry-point”. We can’t have Order Lines without an Order that contains them and obviously an Order without Order Lines is pretty useless.

At the same time, you can’t access Order Lines from the outside world without going through the Order.

Clear? Definitely not rocket science.

Why “aggregate” ? Well, because you’re combining things together and building up a structure that mimics your current domain. The Order and the Order Lines are entities and value objects that will eventually form the Aggregate.

I’ll talk more about the distinction between Entities and Value Objects in another post, for now just take that for granted (or lookup on Google!).

For now just think that eventually your system will be a composition of multiple Aggregates acting and interacting together, and the quality of their interaction will be a representation of how good you know your Domain. Communication is the key here!

At this point I would say that the trick is to find the right balance and being able to identify the right boundaries for your Aggregates. Why? Simply because of divide-et-impera.

Our domain might be complex from the beginning, or become extremely complex over time. Everybody has seen this happening at some point. So take a deep breath, talk to your Domain Expert ™ and identify what are the edges and the sets of your entities. That’s it. Compartmentalize.

There’s a lot more to write on this, and I definitely will. When? That’s definitely a good question! A lot is going on in my life these days and weeks and I have the sensation that 2019 is going to be a crucial year for everyone here.

Ciao!

© 2019 Davide Guida

Theme by Anders NorenUp ↑