转换cognito group
为claim role
使用IClaimsTransformation
:
public class ClaimsTransformer : IClaimsTransformation
{
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
var claims = new List<Claim>();
var cognitoClaims = principal.Claims.Where(t => t.Type == "cognito:groups").ToList();
foreach (var claim in cognitoClaims)
{
var claim2 = new Claim(ClaimTypes.Role, claim.Value);
claims.Add(claim2);
}
var claimsIdentity = new ClaimsIdentity(claims, IdentityConstants.ApplicationScheme);
return new ClaimsPrincipal(claimsIdentity);
}
}
注册到Startup\ConfigureServices
:
public void ConfigureServices(IServiceCollection services)
{
// Adds Amazon Cognito as Identity Provider
//services.AddCognitoIdentity();
services.AddAuthentication("Bearer")
.AddJwtBearer(options =>
{
options.Audience = "aws-app-client-id";
options.Authority = "https://cognito-idp.us-east-1.amazonaws.com/aws-pool-id";
});
services.AddScoped<IClaimsTransformation, ClaimsTransformer>();
services.AddControllers();
}
令牌由 cognito 用户名和密码生成:
[HttpGet]
[Route("{username}/{password}")]
public async Task<string> Get(string username, string password)
{
var provider = new AmazonCognitoIdentityProviderClient(RegionEndpoint.USEast1);
var pool = new CognitoUserPool(poolId, clientId, provider);
var user = new CognitoUser(userId, clientId, pool, provider);
var request = new InitiateSrpAuthRequest
{
Password="cognito-password"
};
AuthFlowResponse response = await user.StartWithSrpAuthAsync(request);
return response.AuthenticationResult.IdToken ;
}