【问题标题】:Get token and user details after token is issued in controller method在控制器方法中发出令牌后获取令牌和用户详细信息
【发布时间】:2018-03-12 06:49:14
【问题描述】:

我在我的 web api 应用程序中使用 Asp.net Identity 进行基于令牌的身份验证。问题是我必须在生成令牌之后执行一些操作并且用户通过身份验证在重定向到客户端之前发生。

我有一个使用 /token token authentication 的登录页面。颁发令牌后,我需要将用户和令牌值保留在会话中。 [此会话将用于显示在线用户。]

客户请求

 $('#btnLogin').click(function () {
            $.ajax({
                // Post username, password & the grant type to /token
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    username: $('#txtUsername').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                }
});

服务器端

[HttpPost]
    public void Login()
    {
     OnlineUsers user = new OnlineUsers();
     var users = (HttpContext.Current.Session["ActiveUsers"] as 
     List<OnlineUsers>) ?? new List<OnlineUsers>();
     users.Add(user);
     HttpContext.Current.Session["ActiveUsers"] = users;
    }

我需要在颁发令牌并验证使用后调用此控制器方法。 有什么解决办法吗?

【问题讨论】:

  • 如果您能提供minimal reproducible example,那就太好了。
  • 我添加了对我想要实现的目标的最小描述
  • 您应该提供一些代码来显示您尝试过的内容...
  • 包含代码

标签: c# asp.net asp.net-identity


【解决方案1】:

如果您想拦截令牌的生成,认为您必须自定义 aspnet 身份行为

https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.usermanagerextensions.generateusertoken(v=vs.108).aspx

【讨论】:

    【解决方案2】:

    Web API 使用会话不是一个好方法,为了将用户信息保存在客户端,您可以使用浏览器的本地存储。一旦用户通过您的登录 api 控制器进行身份验证,您可以将用户所需的信息以 json 格式返回给客户端,然后您可以将其保存到浏览器。 Web API 默认是无状态的,所以我认为 session 不适合它,给客户端增加了负担。 在服务器上存储会话状态违反了 REST 架构的无状态约束。所以会话状态必须完全由客户端处理。

    网络 API

    [HttpPost]
    public IHttpActionResultLogin()
    {
         OnlineUsers user = new OnlineUsers();
         user=YourUserDetailsMethod();
         return Ok(user);
    }
    

    客户:

    $('#btnLogin').click(function () {
            $.ajax({
                // Post username, password & the grant type to /token
                url: '/token',
                method: 'POST',
                contentType: 'application/json',
                data: {
                    username: $('#txtUsername').val(),
                    password: $('#txtPassword').val(),
                    grant_type: 'password'
                },
                success: function(response){
                    window.localStorage.setItem('userInfo', response);
                    $('#UserName').val(window.localStorage.getItem('userInfo').UserName);
                }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-02
      • 2018-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 2019-01-03
      • 2016-05-05
      • 2016-11-29
      相关资源
      最近更新 更多