简体   繁体   中英

JWT Authorization in .net Core - communicate with OAuth server

I start building new application with JWT authorization. Our team already have OAuth 2 server written in java, so my target is: check key with public key. But I don't know how to do it. If I use .net identity I have to use entity framework but I use only Cassandra as a database.

How I can implement it without using EF? Do you know any tutorials?

You don't need any ASP.NET Core stuff. A simple approach would be:

Nu-get the Packages

System.IdentityModel.Tokens.Jwt,
Microsoft.IdentityModel.Tokens

Set up some validation parameters:

var validationParameters = new TokenValidationParameters
{
    RequireExpirationTime = true,
    ValidateLifetime = true,
    IssuerSigningKeys = keys, // Your public keys.
    ValidAudience = "my valid audience",
    ValidIssuer = "my valid issuer"
}

Call ValidateToken to get a ClaimsPrincipal with claims and stuff. token is your JWT string, eg parsed from Authorization HTTP header.

var handler = new JwtSecurityTokenHandler();
handler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);

Using JsonWebKeySet from the above IdentityModel.Tokens package, you can automagically obtain keys from an OpenID Connect configuration:

https://github.com/IdentityModel/IdentityModel/blob/master/source/IdentityModel.Shared/Jwt/JsonWebKeySet.cs

There are quite a few Microsoft (and other) documents available (make sure you are looking at documents relevant to the version that you are working with!) - googling will find them pretty easily, but EF is certainly not required as seen below.

No identity or user information is managed by the app directly. Instead, it will get all the user information it needs directly from the JWT token that authenticates a caller. https://blogs.msdn.microsoft.com/webdev/2017/04/06/jwt-validation-and-authorization-in-asp-net-core/

Here is a simple example for version 1.1 https://github.com/williamhallatt/aspnet-core-webapi-jwt-auth-example

and the same example for 2.0 https://github.com/williamhallatt/aspnet-core-webapi-jwt-auth-example/tree/dotnecore2.0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM