[英]How to get JWTToken from ASPNET Core Controller?
I'm trying to make a request to a protected API, so I need to add a authorization request header to HttpClient like this:我正在尝试向受保护的 API 发出请求,因此我需要向 HttpClient 添加一个授权请求标头,如下所示:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "Your Oauth token");
But how to get the Authentication Token ("Your Oauth token") from a controller?但是如何从控制器获取身份验证令牌(“您的 Oauth 令牌”)?
PS: I am already authenticated to Identity Server 4. Application developed in AspNetCore. PS:我已经通过了 Identity Server 4 的身份验证。在 AspNetCore 中开发的应用程序。
Full code:完整代码:
[Authorize] //Already authenticated
public IActionResult SomeControllerAction()
{
var claimsIdentity = User.Identity as ClaimsIdentity; //where is JWTToken??
var JWTTokne = "how to get?";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", JWTTokne);
var result = client.PostAsync("someurl", new StringContent(json, Encoding.UTF8, "application/json")).Result;
//more code to handle result....
}
return View();
}
you can get the access token by using:您可以使用以下方法获取访问令牌:
// Get the access token.
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
var client = new HttpClient();
// Set the access token as the bearer token (Authorization header of the request).
client.SetBearerToken(accessToken);
Core:核心:
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token");
Or this:或者这个:
var token = Request.Headers["Authorization"];
For access_token in MVC 5 controller I used:对于 MVC 5 控制器中的 access_token,我使用了:
var token = (User as ClaimsPrincipal).FindFirst("access_token").Value
In the protected web api 2 (not core) method I used:在受保护的 web api 2(非核心)方法中,我使用了:
var access_token = ControllerContext.Request.Headers.Authorization.Parameter;
You can look at the HTTP Context since you're in a controller you can just get the token from the Header at HttpContext.Request.Headers["Authorization"]
.您可以查看 HTTP 上下文,因为您在控制器中,您只需从
HttpContext.Request.Headers["Authorization"]
的 Header 中获取令牌。 This obviously only works if the client has put that header in the request.这显然仅在客户端将该标头放入请求中时才有效。
With AspNet Core 2.0 and the new authentication system, you simply use the extension methods ontop of HttpContext.使用 AspNet Core 2.0 和新的身份验证系统,您只需使用 HttpContext 之上的扩展方法。
HttpContext context;
await context.GetTokenAsync("access_token")
and in a MVC controller并在 MVC 控制器中
public class MyController : Controller
{
public IActionResult Get(){
var token = await HttpContext.GetTokenAsync("access_token");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.