我正在尝试通过客户端凭据获取访问令牌以使用office365 api。我正在使用本指南:Office 365 Rest API - Daemon week authentication
我是用邮递员发送请求的(见下文) Postman Picture
但是当我发送请求“AADSTS70002:验证凭据时出错.AADSTS50012:客户端断言包含无效签名”时,邮递员会给我这个错误
所以我很确定我没有正确签署JWT,这是我请求中的client_assertion参数。参考这个堆栈溢出问题Could not retrieve app only tokens for office 365我发现我需要使用RSA SHA-256哈希对其进行签名。但是我仍然无法让我的JWT使用我在网上找到的关于如何执行此操作的任何资源,它仍会返回相同的错误。是否有一个在线生成器,我可以使用RSA SHA-256哈希来签署我的JWT?或者任何专门用这种方式在C#中唱歌的代码示例?提前谢谢。
答案 0 :(得分:1)
首先,您需要在Azure AD清单上设置证书,请参阅博客Building Daemon or Service Apps with Office 365 Mail, Calendar, and Contacts APIs (OAuth2 client credential flow)
关于如何签署令牌,这里是C#示例供您参考,
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);
您也可以在GitHub上找到该项目
https://github.com/dream-365/OfficeDev-Samples/blob/master/samples/Office365DevQuickStart/JWT-Token
答案 1 :(得分:1)
您还可以使用https://github.com/jwtk/jjwt
中给出的JJWT apis签署您的JWT令牌示例代码可能如下所示:
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();
您还可以在JWT.io
上验证您的令牌