[英]Can I retrieve userinfo from bearer token on server side — web api 2?
Here is my scenario: I have a MVC web application and Web API. 这是我的场景:我有一个MVC Web应用程序和Web API。 Web application making calls to web api for saving/retrieving data from server.
Web应用程序调用web api以保存/检索服务器中的数据。
Lets say this is a question/answer web site. 让我们说这是一个问答网站。 Right now I have an API that gives me userid if I provide username, password.
现在我有一个API,如果我提供用户名,密码,它会给我userid。 But there are other areas in the website and its easy to retrieve other user's userid.
但是网站中还有其他区域,并且很容易检索其他用户的用户ID。 I'm keeping the userid in the session storage and sending that in the POST object wherever required.
我将userid保留在会话存储中,并在POST对象中将其发送到需要的地方。 Now any user can tweak that userid in the session storage and they can post the question/answer on behalf of other user.
现在,任何用户都可以在会话存储中调整该用户ID,并且他们可以代表其他用户发布问题/答案。
How I can prevent this? 我怎么能阻止这个? One approach I was thinking but not sure if this is feasible solution - can we retrieve the userid from the supplied bearer token on the server side?
我正在思考但不确定这是否是可行解决方案的一种方法 - 我们可以从服务器端提供的承载令牌中检索用户ID吗?
Sure you can do this, once you establish token based authentication in Web API using the resource owner credential flow, and when you attribute you protected controllers with [Authorize]
. 当您使用资源所有者凭据流在Web API中建立基于令牌的身份验证时,以及使用
[Authorize]
将受保护的控制器归属时,您确实可以执行此操作。 The valid bearer token you will send to this protected endpoint will create ClaimsPrincipal
principal (identity) object where the user is stored in it, you can get the username as the below: 您将发送到此受保护端点的有效承载令牌将创建用户存储在其中的
ClaimsPrincipal
主体(标识)对象,您可以获得如下的用户名:
[RoutePrefix("api/Orders")]
public class OrdersController : ApiController
{
[Authorize]
[Route("")]
public IHttpActionResult Get()
{
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var Name = ClaimsPrincipal.Current.Identity.Name;
var Name1 = User.Identity.Name;
return Ok();
}
}
For more detailed information about this you can read my detailed posts about this topic here . 有关这方面的更多详细信息,请在此处阅读有关此主题的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.