Get bearer token in ASP.NET WebAPI

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

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

  • As far as I know, the bearer token is not stored in the database. Can it get the ASP.NET API somehow?

  • I would also like to create this user from code and store the token somehow, because I need to deploy the database to multiple servers.

+4


source to share


2 answers


I do not recommend using this approach if you only have one client talking to your API, I understand that you need to issue a very long lived access token, perhaps for a year, and continue to use that token to access the reverse-end API , is not it? What will you do if this token is stolen? You cannot revoke an access token, so it somehow resembles your master key (password). My recommendation is to use OAuth refresh tokens along with access tokens. It depends on your client type, you can check how it is done here http://bitoftech.net/2014/07/16/enable-oauth-refresh-tokens-angularjs-app-using-asp-net-web-api -2-owin / Light tokens can be canceled and they can expire after a very long time. Let me know if you need more information to implement this.



+5


source


Create a custom authentication attribute and store token hashes for users. A user can have multiple tokens. You can then let the user do what he wants - log out of all other sessions when the password is changed, or selectively delete sessions



  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);

        }
    }

      

0


source







All Articles