The following code gives me Azure AD security token
, I need to validate that token is valid or not. How to achieve this?
// Get OAuth token using client credentials
string tenantName = "mytest.onmicrosoft.com";
string authString = "https://login.microsoftonline.com/" + tenantName;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
string clientId = "fffff33-6666-4888-a4tt-fbttt44444";
string key = "123v47o=";
ClientCredential clientCred = new ClientCredential(clientId, key);
string resource = "http://mytest.westus.cloudapp.azure.com";
string token;
Task<AuthenticationResult> authenticationResult = authenticationContext.AcquireTokenAsync(resource, clientCred);
token = authenticationResult.Result.AccessToken;
Console.WriteLine(token);
// How can I validate this token inside my service?
Just wanted to add to Fei's answer for people using .net Core 2.0
You'll have to modify 2 lines of the
Validate(string token)
method.There are two steps to verify the token. First, verify the signature of the token to ensure the token was issued by Azure Active Directory. Second, verify the claims in the token based on the business logic.
For example, we need to verify the
iss
andaud
claim if you were developing a single tenant app. And you also need to verify thenbf
to ensure the token is not expired. More claims you can refer here.Below description is from here about the detail of signature verifying. (Note: The example below uses the Azure AD v2 endpoint. You should use the endpoint that corresponds to the endpoint the client app is using.)
Then we can use the
JwtSecurityTokenHandler
to verify the token using the sample code below:And if you were using the OWIN components in your project, it is more easy to verify the token. We can use the code below to verify the token:
Then we can use the code below to verify the ‘scope’ in the token:
And here is a code sample which protected the web API with Azure AD:
Protect a Web API using Bearer tokens from Azure AD
But if you are not using OWIN in your projects, it is going to be a little hard or at least time consuming.. This articleHere is great resource.
And because I do not have much to add on the above, except the detailed code.. Here is something that can be useful to you:
There are some functions that I use in here that are not available for you, they are self descriptive.