具有.NET核心Web API的OAuth Angular SPA代码授权
目前正在我们的.NET核心Web API中实现AzureAD身份验证。这需要与Angular 7前端交互,与另一个域上的API交互 在以前用PHP编写的应用程序迭代中,我们的身份验证流程是:具有.NET核心Web API的OAuth Angular SPA代码授权,angular,authentication,asp.net-core,oauth,azure-active-directory,Angular,Authentication,Asp.net Core,Oauth,Azure Active Directory,目前正在我们的.NET核心Web API中实现AzureAD身份验证。这需要与Angular 7前端交互,与另一个域上的API交互 在以前用PHP编写的应用程序迭代中,我们的身份验证流程是: 前端将未经身份验证的用户重定向到,但在此基础上,没有多少运气得到同样的想法 [HttpGet(nameof(Login))] [AllowAnonymous] public IActionResult Login() { return Challenge(new AuthenticationProp
,但在此基础上,没有多少运气得到同样的想法
[HttpGet(nameof(Login))]
[AllowAnonymous]
public IActionResult Login()
{
return Challenge(new AuthenticationProperties
{
RedirectUri = "/api/auth/postcallback"
}, "azuread");
}
[HttpGet(nameof(PostCallback))]
[Authorize]
public IActionResult PostCallback()
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Tokens:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(HttpContext.User.Claims),
Expires = DateTime.UtcNow.AddHours(6),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new JsonResult(new { token = tokenHandler.WriteToken(token) });
}
var auth = services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
auth.AddCookie();
auth.AddJwtBearer(opt =>
{
opt.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ClockSkew = TimeSpan.FromHours(6),
ValidateLifetime = true
};
});
auth.AddOAuth("azuread", opt =>
{
opt.ClientId = Configuration["Auth:ClientId"];
opt.ClientSecret = Configuration["Auth:ClientSecret"];
opt.CallbackPath = "/api/auth/callback";
opt.AuthorizationEndpoint = Configuration["Auth:AuthEndpoint"];
opt.TokenEndpoint = Configuration["Auth:TokenEndpoint"];
opt.UserInformationEndpoint = Configuration["Auth:UserInformationEndpoint"];
// claims/scopes/events removed from here
});
[HttpGet(nameof(Callback))]
[AllowAnonymous]
public async Task<IActionResult> Callback()
{
var result = await HttpContext.AuthenticateAsync();
await HttpContext.SignInAsync(result.Principal);
if(!result.Succeeded)
{
return Unauthorized();
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Tokens:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(HttpContext.User.Claims),
Expires = DateTime.UtcNow.AddHours(6),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return new JsonResult(new { token = tokenHandler.WriteToken(token) });
}