如何在 identityserver4 中没有用户名和密码的情况下从令牌端点获取令牌?
how can I get token from token endpoint without username and password in identityserver4?
我在 asp.net 核心网络 api.I 中使用 IdentityServer4 进行用户身份验证和授权 api.I 在 android application.My 用户中使用此 api 注册和使用用户名和密码登录没问题。这是我从 connect/token 端点
获得的访问令牌
{
"alg": "RS512",
"typ": "at+jwt"
}
{
"nbf": 1600324303,
"exp": 1631860303,
"iss": "https://myIdentityServerApi.com",
"aud": [
"IdentityServerApi",
"MyAPI1"
],
"client_id": "MyApp1",
"sub": "521d198c-3657-488e-997e-3e50d756b353",
"auth_time": 1600324302,
"idp": "local",
"role": "Admin",
"name": "myusername",
"scope": [
"openid",
"IdentityServerApi",
"MyAPI1"
],
"amr": [
"pwd"
]
}
现在在我的新 android 应用程序中,我希望用户使用 phone 号码和短信激活进行注册和登录。
当用户发送 ActivationCode 时,我应该向他发送访问权限 token.But 如何在没有用户名和密码的情况下从令牌端点获取令牌?
在下面我想生成令牌manually.but生成的令牌不起作用。
[HttpPost("Activate")]
[AllowAnonymous]
public async Task<IActionResult> Activate([FromBody] SignUpPhoneModel model)
{
if (string.IsNullOrWhiteSpace(model.PhoneNumber))
{
return BadRequest("Phone Number is Empty");
}
PhoneValidation pv = new PhoneValidation();
IdentityUser CurrentUser = await db.Users.Where(e => e.PhoneNumber == model.PhoneNumber).FirstAsync();
if (!await UserManager.VerifyChangePhoneNumberTokenAsync(CurrentUser, model.ActivationCode, model.PhoneNumber))
{
return BadRequest("Activation Code is not correct");
}
else
{
//Here user is activated and should get token But How?
CurrentUser.PhoneNumberConfirmed = true;
List<string> UserRoles = (await UserManager.GetRolesAsync(CurrentUser)).ToList();
var tokenHandler = new JwtSecurityTokenHandler();
RSACryptoServiceProvider rsap = new RSACryptoServiceProvider(KeyContainerNameForSigning);
SecurityKey sk = new RsaSecurityKey(rsap.Engine);
List<Claim> UserClaims = new List<Claim>() {
new Claim(JwtRegisteredClaimNames.Sub, CurrentUser.Id),
};
foreach (var r in UserRoles)
{
UserClaims.Add(new Claim(JwtClaimTypes.Role, r));
}
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer= "https://myidentityserverapi.com",
Audience = "IdentityServerApi,MyAPI",
Subject = new ClaimsIdentity(UserClaims),
Expires = DateTime.UtcNow.AddDays(365),
SigningCredentials = new SigningCredentials(sk, SecurityAlgorithms.RsaSha512),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
TokenModel tm = new TokenModel()
{
access_token = tokenHandler.WriteToken(token)
};
return Ok(tm);
}
}
当我在我的应用程序中从上面(actionvation 方法)收到令牌时,如下所示,但它不起作用,例如 User.Identity.IsAuthenticated
是 false.Does 任何人都知道我如何生成令牌connect/token 端点没有用户名和密码?
"alg": "RS256",
"typ": "JWT"
}
{
"unique_name": "13f2e130-e2e6-48c7-b3ac-40f8dde8087b",
"role": "Member",
"nbf": 1600323833,
"exp": 1718259833,
"iat": 1600323833
}
我选对了方法吗?或者我应该使用另一种方式,例如不同的流程或授权类型?
我认为您需要做的就是当用户确认激活码时,您将执行与以下内容相同的操作:
public async Task<IActionResult> Login(LoginInputModel model, string button) { }
在参考文献中找到 AccountController.cs class。
我想您的用户通过 IS4 服务器激活了他们的 ActivationCode
。如果是这种情况,您不需要 manage/generate 手动 access_token
.
您只需遵循与 AccountController 中的 Login
方法相同的过程,包括:
使用 login/password 检查用户,在您的情况下验证您的 ActivationCode
一旦用户被识别,SignIn
您的用户将通过 SignInManager。 (SignInManager.SignInAsync)
引发 UserLoginSuccessEvent 事件。
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
最终将用户重定向到您的网络应用程序。
return Redirect(model.ReturnUrl);
重定向到您的应用程序时,IdentityServer4 将向用户发送其 access_token
。
我终于像这样创建了访问令牌:
[HttpPost("Activate")]
[AllowAnonymous]
public async Task<IActionResult> Activate([FromBody] SignUpPhoneModel model, [FromServices] ITokenService TS, [FromServices] IUserClaimsPrincipalFactory<JooyaIdentityUser> principalFactory, [FromServices] IdentityServerOptions options)
{
JooyaIdentityUser CurrentUser = await db.Users.Where(e => e.PhoneNumber == model.PhoneNumber).FirstOrDefaultAsync();
if (!await UserManager.VerifyChangePhoneNumberTokenAsync(CurrentUser, model.ActivationCode, model.PhoneNumber))
{
return BadRequest("Activation Code in not correct");
}
CurrentUser.PhoneNumberConfirmed = true;
await db.SaveChangesAsync();
await UserManager.UpdateSecurityStampAsync(CurrentUser);
var Request = new TokenCreationRequest();
var IdentityPricipal = await principalFactory.CreateAsync(CurrentUser);
var IdentityUser = new IdentityServerUser(CurrentUser.Id.ToString());
IdentityUser.AdditionalClaims = IdentityPricipal.Claims.ToArray();
IdentityUser.DisplayName = CurrentUser.UserName;
IdentityUser.AuthenticationTime = System.DateTime.UtcNow;
IdentityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider;
Request.Subject = IdentityUser.CreatePrincipal();
Request.IncludeAllIdentityClaims = true;
Request.ValidatedRequest = new ValidatedRequest();
Request.ValidatedRequest.Subject = Request.Subject;
Request.ValidatedRequest.SetClient(SeedConfig.GetClients().Where(e => e.ClientId == model.ClientId).First());
List<ApiResource> Apis = new List<ApiResource>();
Apis.Add(SeedConfig.GetApis().Where(e => e.Name == "IdentityServerApi").First());
Apis.Add(SeedConfig.GetApis().Where(e => e.Name == model.ApiName).First());
Request.Resources = new Resources(SeedConfig.GetIdentityResources(), Apis);
Request.ValidatedRequest.Options = options;
Request.ValidatedRequest.ClientClaims = IdentityUser.AdditionalClaims;
var Token = await TS.CreateAccessTokenAsync(Request);
Token.Issuer = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value;
Token.Lifetime = 32000000;
var TokenValue = await TS.CreateSecurityTokenAsync(Token);
TokenModel tm = new TokenModel()
{
access_token = TokenValue
};
return Ok(tm);
}
我在 asp.net 核心网络 api.I 中使用 IdentityServer4 进行用户身份验证和授权 api.I 在 android application.My 用户中使用此 api 注册和使用用户名和密码登录没问题。这是我从 connect/token 端点
获得的访问令牌{
"alg": "RS512",
"typ": "at+jwt"
}
{
"nbf": 1600324303,
"exp": 1631860303,
"iss": "https://myIdentityServerApi.com",
"aud": [
"IdentityServerApi",
"MyAPI1"
],
"client_id": "MyApp1",
"sub": "521d198c-3657-488e-997e-3e50d756b353",
"auth_time": 1600324302,
"idp": "local",
"role": "Admin",
"name": "myusername",
"scope": [
"openid",
"IdentityServerApi",
"MyAPI1"
],
"amr": [
"pwd"
]
}
现在在我的新 android 应用程序中,我希望用户使用 phone 号码和短信激活进行注册和登录。 当用户发送 ActivationCode 时,我应该向他发送访问权限 token.But 如何在没有用户名和密码的情况下从令牌端点获取令牌?
在下面我想生成令牌manually.but生成的令牌不起作用。
[HttpPost("Activate")]
[AllowAnonymous]
public async Task<IActionResult> Activate([FromBody] SignUpPhoneModel model)
{
if (string.IsNullOrWhiteSpace(model.PhoneNumber))
{
return BadRequest("Phone Number is Empty");
}
PhoneValidation pv = new PhoneValidation();
IdentityUser CurrentUser = await db.Users.Where(e => e.PhoneNumber == model.PhoneNumber).FirstAsync();
if (!await UserManager.VerifyChangePhoneNumberTokenAsync(CurrentUser, model.ActivationCode, model.PhoneNumber))
{
return BadRequest("Activation Code is not correct");
}
else
{
//Here user is activated and should get token But How?
CurrentUser.PhoneNumberConfirmed = true;
List<string> UserRoles = (await UserManager.GetRolesAsync(CurrentUser)).ToList();
var tokenHandler = new JwtSecurityTokenHandler();
RSACryptoServiceProvider rsap = new RSACryptoServiceProvider(KeyContainerNameForSigning);
SecurityKey sk = new RsaSecurityKey(rsap.Engine);
List<Claim> UserClaims = new List<Claim>() {
new Claim(JwtRegisteredClaimNames.Sub, CurrentUser.Id),
};
foreach (var r in UserRoles)
{
UserClaims.Add(new Claim(JwtClaimTypes.Role, r));
}
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer= "https://myidentityserverapi.com",
Audience = "IdentityServerApi,MyAPI",
Subject = new ClaimsIdentity(UserClaims),
Expires = DateTime.UtcNow.AddDays(365),
SigningCredentials = new SigningCredentials(sk, SecurityAlgorithms.RsaSha512),
};
var token = tokenHandler.CreateToken(tokenDescriptor);
TokenModel tm = new TokenModel()
{
access_token = tokenHandler.WriteToken(token)
};
return Ok(tm);
}
}
当我在我的应用程序中从上面(actionvation 方法)收到令牌时,如下所示,但它不起作用,例如 User.Identity.IsAuthenticated
是 false.Does 任何人都知道我如何生成令牌connect/token 端点没有用户名和密码?
"alg": "RS256",
"typ": "JWT"
}
{
"unique_name": "13f2e130-e2e6-48c7-b3ac-40f8dde8087b",
"role": "Member",
"nbf": 1600323833,
"exp": 1718259833,
"iat": 1600323833
}
我选对了方法吗?或者我应该使用另一种方式,例如不同的流程或授权类型?
我认为您需要做的就是当用户确认激活码时,您将执行与以下内容相同的操作:
public async Task<IActionResult> Login(LoginInputModel model, string button) { }
在参考文献中找到 AccountController.cs class。
我想您的用户通过 IS4 服务器激活了他们的 ActivationCode
。如果是这种情况,您不需要 manage/generate 手动 access_token
.
您只需遵循与 AccountController 中的 Login
方法相同的过程,包括:
使用 login/password 检查用户,在您的情况下验证您的
ActivationCode
一旦用户被识别,
SignIn
您的用户将通过 SignInManager。 (SignInManager.SignInAsync)引发 UserLoginSuccessEvent 事件。
await _events.RaiseAsync(new UserLoginSuccessEvent(user.UserName, user.Id, user.UserName, clientId: context?.Client.ClientId));
最终将用户重定向到您的网络应用程序。
return Redirect(model.ReturnUrl);
重定向到您的应用程序时,IdentityServer4 将向用户发送其 access_token
。
我终于像这样创建了访问令牌:
[HttpPost("Activate")]
[AllowAnonymous]
public async Task<IActionResult> Activate([FromBody] SignUpPhoneModel model, [FromServices] ITokenService TS, [FromServices] IUserClaimsPrincipalFactory<JooyaIdentityUser> principalFactory, [FromServices] IdentityServerOptions options)
{
JooyaIdentityUser CurrentUser = await db.Users.Where(e => e.PhoneNumber == model.PhoneNumber).FirstOrDefaultAsync();
if (!await UserManager.VerifyChangePhoneNumberTokenAsync(CurrentUser, model.ActivationCode, model.PhoneNumber))
{
return BadRequest("Activation Code in not correct");
}
CurrentUser.PhoneNumberConfirmed = true;
await db.SaveChangesAsync();
await UserManager.UpdateSecurityStampAsync(CurrentUser);
var Request = new TokenCreationRequest();
var IdentityPricipal = await principalFactory.CreateAsync(CurrentUser);
var IdentityUser = new IdentityServerUser(CurrentUser.Id.ToString());
IdentityUser.AdditionalClaims = IdentityPricipal.Claims.ToArray();
IdentityUser.DisplayName = CurrentUser.UserName;
IdentityUser.AuthenticationTime = System.DateTime.UtcNow;
IdentityUser.IdentityProvider = IdentityServerConstants.LocalIdentityProvider;
Request.Subject = IdentityUser.CreatePrincipal();
Request.IncludeAllIdentityClaims = true;
Request.ValidatedRequest = new ValidatedRequest();
Request.ValidatedRequest.Subject = Request.Subject;
Request.ValidatedRequest.SetClient(SeedConfig.GetClients().Where(e => e.ClientId == model.ClientId).First());
List<ApiResource> Apis = new List<ApiResource>();
Apis.Add(SeedConfig.GetApis().Where(e => e.Name == "IdentityServerApi").First());
Apis.Add(SeedConfig.GetApis().Where(e => e.Name == model.ApiName).First());
Request.Resources = new Resources(SeedConfig.GetIdentityResources(), Apis);
Request.ValidatedRequest.Options = options;
Request.ValidatedRequest.ClientClaims = IdentityUser.AdditionalClaims;
var Token = await TS.CreateAccessTokenAsync(Request);
Token.Issuer = HttpContext.Request.Scheme + "://" + HttpContext.Request.Host.Value;
Token.Lifetime = 32000000;
var TokenValue = await TS.CreateSecurityTokenAsync(Token);
TokenModel tm = new TokenModel()
{
access_token = TokenValue
};
return Ok(tm);
}