Retrieve bearer token in ASP.NET WebAPI

谁都会走 提交于 2020-01-02 06:20:18

问题


I have a Web API with authentication enabled (bearer token). This is called by a client application and I want to protect it from anonymous usage so I would like to create a single user and create a bearer token for it.

I can create the token by calling the register and token methods, but I would like to do this from code.

  1. As far as I know, the bearer token is not stored in the database. Can it be retrieved somehow using the ASP.NET Identity API ?

  2. I would also like to create this user from code and save the token somewehere because I need to deploy the database to multiple servers.


回答1:


I do not recommend going with this approach if you have only one client which will talk to your API, my understanding that you need to issue very very long lived access token maybe for a year and keep using this token to access the back-end API, right? What you will do if this token is stolen? You can't revoke the access token, so it is somehow like your master key (password). My recommendation is to use OAuth refresh tokens along with access tokens. This depend on the type of your client, you can check how this is done here http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api-2-owin/ The refresh tokens can be revoked and they can expire after very long time. Let me know if you need further details to implement this.




回答2:


Create a Custom Authentication Attribute and store the token hashes for users. A user can have multiple tokens. Then you can let user do what he wants - log out all other sessions when password is changed or remove sessions selectively

  public class CustomAuthAttribute : System.Web.Http.AuthorizeAttribute
    {
        protected override bool IsAuthorized(HttpActionContext context)
        {
            var accessToken = HttpContext.Current.Request.Headers["Authorization"];
            var hash = accessToken.Md5();
            //store the hash for that user 
            //check if the hash is created before the password change or its session was removed by the user
            //store IP address and user agent 
            var isBlackListed = ...
            .....
            return !isBlackListed && base.IsAuthorized(context);

        }
    }


来源:https://stackoverflow.com/questions/25764732/retrieve-bearer-token-in-asp-net-webapi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!