How to sign JWT with a RSA SHA-256 hash - oauth-2.0

I'm trying to get an access token to use office365 api through client credentials. I'm using this guide: Office 365 Rest API - Daemon week authentication
I'm sending my request using postman (see below)
Postman Picture
However postman gives me this error when I send the request "AADSTS70002: Error validating credentials. AADSTS50012: Client assertion contains an invalid signature"
So I'm fairly certain I'm not signing the JWT correctly which is used for the client_assertion parameter in my request. Referring to this stack overflow question Could not retrieve app only tokens for office 365 I found that I need to sign it using a RSA SHA-256 hash. However I still couldn't get my JWT to work with any of the resources I found online on how to do this, it still would come back with the same error. Is there an online generator I can use to sign my JWT using a RSA SHA-256 hash? Or any code examples that specifically do this way of singing in C#? Thanks in advance.

First, you need to set up the certificates on Azure AD manifest, see blog Building Daemon or Service Apps with Office 365 Mail, Calendar, and Contacts APIs (OAuth2 client credential flow)
About how to sign a token, here is the C# sample for your reference,
var x509Certificate2 = new X509Certificate2(#"{FILE PATH}\office_365_app.pfx", "PASS_WORD");
X509SigningCredentials signingCredentials = new X509SigningCredentials(x509Certificate2, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();
var originalIssuer = "{YOUR CLIENT ID}";
var issuer = originalIssuer;
DateTime utcNow = DateTime.UtcNow;
DateTime expired = utcNow + TimeSpan.FromHours(1);
var claims = new List<Claim> {
new Claim("aud", "https://login.microsoftonline.com/{YOUR_TENENT_ID}/oauth2/token", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("exp", "1460534173", ClaimValueTypes.DateTime, issuer, originalIssuer),
new Claim("jti", "{SOME GUID YOU ASSIGN}", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("nbf", "1460533573", ClaimValueTypes.String, issuer, originalIssuer),
new Claim("sub", "{YOUR CLIENT ID}", ClaimValueTypes.String, issuer, originalIssuer)
};
ClaimsIdentity subject = new ClaimsIdentity(claims: claims);
JwtSecurityToken jwtToken = tokenHandler.CreateToken(
issuer: issuer,
signingCredentials: signingCredentials,
subject: subject) as JwtSecurityToken;
jwtToken.Header.Remove("typ");
var token = tokenHandler.WriteToken(jwtToken);
You can also find the project on GitHub
https://github.com/dream-365/OfficeDev-Samples/blob/master/samples/Office365DevQuickStart/JWT-Token

You can also sign your JWT token using JJWT apis given at https://github.com/jwtk/jjwt
The Sample code could look like:
Map<String, Object> claims = new HashMap<>();
claims.put("user", "some user");
Calendar expires = Calendar.getInstance();
expires.roll(Calendar.HOUR, 1000);
Jwts.builder()
.setClaims(claims)
.setIssuedAt(new Date())
.setExpiration(expires.getTime())
.signWith(SignatureAlgorithm.RS256, key)
.compact();
You can also verify your token on JWT.io

Related

Understanding Google OAuth2 Refresh tokens

I previously worked on an OAuth2 application where the logic was to generate a new access token via refresh token once the old one expired.
Now working with Google APIs, I'm not experiencing the same thing. I have received both an access token and refresh token, and after allowing the access token to expire, I attempt to use the refresh token
var myToken = new TokenResponse
{
RefreshToken = sRefreshToken
};
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}
}), "user", myToken);
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = "XYZ",
});
It seems after doing so I can make API calls. But I have tried to retrieve the access/refresh tokens after doing this with:
ACCESS_TOKEN = credentials.Token.AccessToken;
REFRESH_TOKEN = credentials.Token.RefreshToken;
And both the access and refresh tokens are the same as the old ones. I had thought refreshing would generate a new token altogether? Is this not the case?
If the access token expires after 30 minutes and you then just need to pass in the refresh token (but nothing re-generates), what is the point of the refresh token?
I previously worked on an OAuth2 application where the logic was to generate a new access token via refresh token once the old one expired.
This idea also applies to Google access/refresh tokens. But if you're using the .NET client library (as your code snippet suggests), you don't have to perform the refreshes yourself. You can just continue using the UserCredential object and it'll automatically fetch a new access token every ~1h.

Google Refresh_token not generating Access Token once it expires. Refresh_token cannot create a new Access_token

I am trying to access google sheets using Java client Library. First time access token and refresh token are generated and stored in File.(StoredCredential). Once the access token expires new token is not generated with Refresh token. Please suggest what can be done.
Sample Code:
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");

Call Graph API from MVC App

SUMMARY UPDATE:
I got a sample working today thanks to the many good replies. Thanks all. My primary goal was to get current user information (ME) without using secret key. First I just used the secret key from the App Reg and this will authenticate the App and not the user. This does of course not work when calling ME. My next finding was if you want the users token, you still need the App Reg token, and then you request the users token. This requires less permissions on the App Reg, but requires to request two tokens. I ended up skipping ME and just requesting information for a specified user (through the APp Reg permissions):
$"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName"
Both both approaches should be viable. I updated code below with working sample.
I am trying to do a very simple call to graph API to get companyName from current user. Found some samples but they seemed to be very complicated. The MVC app is authenticated trough an Application Registration in AAD.
I guess the application registration needs to be authorized to access Graph API. Or is more needed here? Getting company name should be fairly simple:
https://graph.microsoft.com/v1.0/me?$select=companyName
Does anyone have a snippet for calling the graph API, my best bet would be you need to extract a bearer token from the controller? ALl help is appreciated.
Working snippet:
public async Task<ActionResult> Index()
{
string clientId = "xxx";
string clientSecret = "xxx";
var email = User.Identity.Name;
AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/xxx.onmicrosoft.com/oauth2/token");
ClientCredential creds = new ClientCredential(clientId, clientSecret);
AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
HttpClient http = new HttpClient();
string url = $"https://graph.microsoft.com/v1.0/users/{email}/$select=companyName";
//url = "https://graph.windows.net/xxx.onmicrosoft.com/users?api-version=1.6";
// Append the access token for the Graph API to the Authorization header of the request by using the Bearer scheme.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
HttpResponseMessage response = await http.SendAsync(request);
var json = response.Content.ReadAsStringAsync();
return View();
}
To add one last item, here is a link to an MVC sample on Git that uses an MVC application to send email. It illustrates how to call the MS Graph API to get various pieces of information. Keep in mind, if you are using an application only scenario, ME will not work, the sample illustrates how to obtain a delegated token for a user and use that toke to do work:
https://github.com/microsoftgraph/aspnet-connect-rest-sample
If I am reading this code snippet correctly, You are requesting a application only token for the Graph.Microsoft.Com resource, then attempting to use that toke with this URI:
url = "https://graph.windows.net/thomaseg.onmicrosoft.com/users?api-version=1.6"
This will not work because you are mixing resources, AAD Graph and MS Graph. The ME endpoint does not make since in this scenario because you are using the application only flow. This flow does not support the ME endpoint. ME is designed for use with a delegated token. the ME endpoint represents the signed in user, since and application is not a user, ME is meaningless.
You will need to target the user specifically:
https://graph.microsoft.com/v1.0/Users/[UPN or ID of user]?$select=companyName
Should work if your application has been granted the appropriate permission scopes.

Microsoft Graph API access token's signature verification is failed

I have a Angular 4 site that I’m trying to use Microsoft Graph implicit flow to authenticate users then use token to call our APIs at another endpoint, so I use msal.js to get the access token.
After I bring the access token to my API endpoint and try to valid it, the token cannot be valid. I got a SignatureVerificationFailedException.
My understanding is that the access token is for Microsoft Graph API, not for my APIs, so I cannot valid it. (I can use it to call Graph API without problem)
How can I get a access token(not id token) using msal.js that can be used for my APIs but not Microsoft Graph? Thanks!
The reason I'm sending access token instead of id token to the API endpoint is that I want to get the puid claim from the token, which is not available for id token.
Here is what I was trying to valid the access token I got from client which is using msal.js
const string authority = "https://login.microsoftonline.com/common";
const string audience = "https://graph.microsoft.com";
string issuer = null;
string stsDiscoveryEndpoint = $"{authority}/v2.0/.well-known/openid-configuration";
List<SecurityToken> signingTokens = null;
var configManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint);
var config = await configManager.GetConfigurationAsync();
issuer = config.Issuer;
signingTokens = config.SigningTokens.ToList();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
ValidAudience = audience,
ValidIssuer = issuer,
ValidateIssuer = false,
IssuerSigningTokens = signingTokens,
CertificateValidator = X509CertificateValidator.None
};
try
{
// Validate token.
SecurityToken validatedToken = new JwtSecurityToken();
var claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out validatedToken);
var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
return ExtractAuthenticatedUserFromClaimsIdentity(claimsIdentity);
}
catch (SignatureVerificationFailedException)
{
throw;
}
Thanks,
If you want to get an access token for your API rather than the Microsoft Graph API, you must specify your API as the resource in the token request.
Make sure that:
Your Web API has configured OAuth2Permission Scopes. See here. Configuring a resource application to expose web APIs
Your Client Application has selected permissions to those exposed APIs. Configuring a client application to access web APIs
Finally, make sure you use your Web API's App ID URI or App ID GUID as the resource value in your token request.
Let me know if this helps!

MVC 5 Identity 2 and Web API 2 authorization and call api using bearer token

The following scenario: I have an MVC 5 web app using Identity 2.0 and Web API 2.
Once the user authenticates in MVC 5 he should be able to call a WEB API endpoint let's call it: api/getmydetails using a bearer token.
What I need to know is how can I issue the token for that specific user in MVC 5?
I did solve this.
Here are some screenshots and I will also post the demo solution.
Just a simple mvc 5 with web api support application.
The main thing you have to register and after login. For this demo purpose I registered as admin#domain.com with password Password123*.
If you are not logged in you will not get the token. But once you loggin you will see the token:
After you get the token start Fiddler.
Make a get request to the api/service endpoint. You will get 401 Unauthorized
Here is the description of the request:
Now go to the web app, stage 1 and copy the generated token and add the following Authorization header: Authorization: Bearer token_here please notice the Bearer keyword should be before the token as in the image bellow. Make a new request now:
Now you will get a 200 Ok response. The response is actually the user id and user name that show's you are authorized as that specific user:
You can download the working solution from here:
http://www.filedropper.com/bearertoken
If for some reason the link doesn't work just let me know and I will send it to you.
P.S.
Of course in your app, you can use the generated bearer token to make ajax call to the web api endpoint and get the data, I didn't do that but should be quite easy ...
P.S. 2: To generate the token:
private string GetToken(ApplicationUser userIdentity)
{
if (userIdentity == null)
{
return "no token";
}
if (userIdentity != null)
{
ClaimsIdentity identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, userIdentity.UserName));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userIdentity.Id));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
DateTime currentUtc = DateTime.UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string AccessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return AccessToken;
}
return "no token";
}

Resources