【发布时间】:2021-01-28 19:06:41
【问题描述】:
在我的网络项目中,我想让用户使用用户名/密码和 Microsoft 帐户登录。 技术 - 堆栈:
- Asp.Net Core WebApi
- 角度
- Azure 应用服务
首先我创建了用户名/密码登录。 像这样:
StartUp.cs:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JWTKey"].ToString())),
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true
};
});
登录方式:
public async Task<IActionResult> ClassicAuth(AuthRequest authRequest)
{
tbl_Person person = await _standardRepository.Login(authRequest.Username, authRequest.Password);
if (person != null)
{
var claims = new[]
{
new Claim(ClaimTypes.GivenName, person.PER_T_Firstname),
};
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(_config["JWTKey"].ToString()));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(claims),
Expires = DateTime.Now.AddHours(24),
SigningCredentials = creds
};
var tokenHandler = new JwtSecurityTokenHandler();
var token = tokenHandler.CreateToken(tokenDescriptor);
return Ok(tokenHandler.WriteToken(token));
}
else
return Unauthorized("Invalid login data");
}
并使用 [Authorize] 保护我的 api 端点。到目前为止一切都很好......这很有效。
现在我想使用 Microsoft 帐户添加登录方法。我为此使用 Azure 应用服务身份验证/授权 (https://docs.microsoft.com/de-de/azure/app-service/overview-authentication-authorization)。
我配置了身份验证提供程序,并且能够在我的 Angular 应用程序中使用自定义链接启动身份验证流程:
<a href="https://mysite.azurewebsites.net/.auth/login/microsoftaccount">Login with Microsoft - Account</a>
这行得通,我可以用这个从我的 Angular 应用程序中检索访问令牌:
this.httpClient.get("https://mysite.azurewebsites.net/.auth/me").subscribe(res => {
console.log(res[0].access_token);
});
现在的问题:
access_token 似乎不是有效的 JWT 令牌。如果我复制令牌并转到https://jwt.io/ 它是无效的。
当我将令牌传递给我的 API 时,我得到一个 401 - 响应。 With 似乎是合乎逻辑的,因为我的 API 检查 JWT 令牌是否使用我的自定义 JWT 密钥而不是 Microsoft 的密钥进行签名。
如何使两种登录方法一起工作?我现在可能有一些基本的理解问题。
【问题讨论】:
-
对不起@OPunktSchmidt,之前的解决方案无效。再次检查您的问题后,我更新了一个示例,可能对您有帮助。
标签: azure authentication jwt azure-web-app-service asp.net-core-webapi