我一直致力于迁移单片ASP Core MVC应用程序以使用服务架构设计.MVC前端网站使用HttpClient从ASP Core Web API加载必要的数据.前端MVC应用程序的一小部分还需要使用IdentityServer4(与后端API集成)进行身份验证.这一切都很有效,直到我Authorize在Web API上的控制器或方法上放置了一个属性.我知道我需要以某种方式将用户授权从前端传递到后端才能使其正常工作,但我不确定如何工作.我试过获取access_token:User.FindFirst("access_token")但它返回null.然后我尝试了这个方法,我可以获得令牌:
var client = new HttpClient("url.com");
var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Run Code Online (Sandbox Code Playgroud)
此方法获取令牌但仍未使用后端API进行身份验证.我对这个OpenId/IdentityServer概念很陌生,任何帮助都将不胜感激!
以下是MVC Client Startup类的相关代码:
private void ConfigureAuthentication(IApplicationBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true,
ExpireTimeSpan = TimeSpan.FromMinutes(60)
});
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
AuthenticationScheme = "oidc",
SignInScheme = "Cookies",
Authority = "https://localhost:44348/",
RequireHttpsMetadata = false,
ClientId = "clientid",
ClientSecret = "secret",
ResponseType = "code id_token",
Scope = { "openid", "profile" …Run Code Online (Sandbox Code Playgroud) 我有一个可以匿名访问的 API 方法。我想使用资源授权来确定用户是否具有访问权限。如果对象是“公共的”,则任何人(包括匿名用户)都可以访问它。如果对象是“私有的”,则只能由登录用户查看。如果我在方法上有授权属性,则此逻辑工作正常,但如果没有,则即使用户登录也没有声明。
有没有办法在没有 Authorize 属性的方法中获取用户的声明?
方法如下所示:
[HttpGet]
[Route("name/{name}")]
public async Task<IActionResult> Get(string name)
{
var activity = Repo.GetCommandLineActivity(name);
if (activity == null)
{
return NotFound();
}
var isAuthed = await _authService.AuthorizeAsync(User, activity, new ViewIPublicPrivateRequirement());
if (isAuthed.Succeeded)
{
return Ok(activity);
}
return Unauthorized();
}
Run Code Online (Sandbox Code Playgroud)