179
CHAPTER 5 | Designing and Developing Multi-Container and Microservice-Based .NET Applications
//...
}
}
}
Then, you also need to set authorization with the [Authorize] attribute on any
resource to be accessed
like the microservices, such as in the following Basket microservice controller.
namespace
Microsoft.
eShopOnContainers
.
Services
.
Basket
.
API
.
Controllers
{
[
Route
(
"api/v1/[controller]"
)]
[Authorize]
public
class
BasketController : Controller
{
//...
}
}
The ValidAudiences such as “basket” are correlated with the audience defined in each microservice
with
AddJwtBearer()
at the ConfigureServices()
of the Startup class, such as in the code below.
// prevent from mapping "sub" claim to nameidentifier.
JwtSecurityTokenHandler.
DefaultInboundClaimTypeMap
.
Clear
();
var
identityUrl = Configuration.
GetValue
<
string
>(
"IdentityUrl"
);
services.
AddAuthentication
(options =>
{
options.
DefaultAuthenticateScheme
= JwtBearerDefaults.
AuthenticationScheme
;
options.
DefaultChallengeScheme
= JwtBearerDefaults.
AuthenticationScheme
;
}).
AddJwtBearer
(options =>
{
options.
Authority
= identityUrl;
options.
RequireHttpsMetadata
=
false
;
options.
Audience
=
"basket"
;
});
If you try to access any secured microservice, like the Basket microservice with a ReRoute URL
based
on the API
Gateway like
http://host.docker.internal:5202/api/v1/b/basket/1
, then you’ll get a
401 Unauthorized unless you provide a valid token.
On the other hand,
if a ReRoute URL is
authenticated, Ocelot will invoke whatever downstream scheme is associated with it (the internal
microservice URL).
Dostları ilə paylaş: