使用Windows Auth验证用户身份,然后在ASPNET Core 2.1中生成JWT [英] Use Windows Auth to authenticate user and then generate JWT in ASPNET Core 2.1
问题描述
我有一个ASP.NET Core 2.1 WebApi,在其中实现了JWT身份验证.用户调用api/authentication/authenticate
,在消息正文中传递其用户名/密码,然后获取JWT作为回报,然后他们将其用于访问服务.
I have an ASP.NET Core 2.1 WebApi, in which I have implemented JWT authentication. The user calls api/authentication/authenticate
, passes their username/password in the message body, and gets back a JWT in return which they then use to access the service.
我还需要API接受Windows身份验证-用户将调用api/authentication/windows
而不传递任何用户信息,该服务将检查他们是否在web.config文件中列出的授权用户列表中(如果我是在IIS中托管).如果是这样,则返回JWT令牌,用户可以使用该令牌访问服务.
I also need the API to accept Windows authentication -- the user will call api/authentication/windows
passing no user information, the service will check they are in the list of authorized users as listed in the web.config file (if I am hosting in IIS). If so, return a JWT token and the user can use that to access the service.
当前我正在考虑...
Currently I'm thinking about this...
-
api/authentication/windows
方法将从请求中获取用户名 - 根据授权用户列表检查用户名.如果它们在上面,则返回一个令牌.如果不是,请转到(3)
- 检查授权用户列表中的任何组.如果它们是成员,则返回令牌.如果不是,则返回401未经授权错误
- The
api/authentication/windows
method will get the username from the request - Check the username against the list of authorized users. If they are on it, return a token. If not, go to (3)
- Check against any groups in the authorized users list. If they are a member, return a token. If not, return a 401 Unauthorized error
这是解决此问题的正确方法吗?
Is this the correct way to approach this?
此处非常相似(未回答)的问题:生成JWT令牌Windows身份验证成功进行身份验证
Very similar (unanswered) question here: Generate JWT token on successful authentication with Windows Authentication
推荐答案
如果要同时启用JWT和AD身份验证,则我仍然需要针对Web中的Active Directory验证用户的凭据(用户名/密码) api:
If you want to enable both JWT and AD authentication ,in my option, you still need to validate the user's credential(username/password) against Active Directory in web api :
仅传递用户名无效,因为Web api中没有经过身份验证的用户上下文.
Pass just username won't work since there is no authenticated user context in web api .
验证用户凭证后,您可以照常生成jwt令牌,例如,如果使用HS256:
After validating user credential , you can generate jwt token as usual , for example if using HS256:
private string BuildToken()
{
var claims = new[] {
new Claim(JwtRegisteredClaimNames.NameId,"name1"),
new Claim(JwtRegisteredClaimNames.Sub,"name1"),
new Claim("customer","customer1"),
new Claim(JwtRegisteredClaimNames.Email,"wuxiyuan@sina,com"),
new Claim("role","user"),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Youkey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken("name1",
"name1",
claims,
expires: DateTime.Now.AddDays(1),
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
这篇关于使用Windows Auth验证用户身份,然后在ASPNET Core 2.1中生成JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!