承载令牌如何存储在服务器端的Web API 2? [英] How are bearer tokens stored server-side in Web API 2?

查看:171
本文介绍了承载令牌如何存储在服务器端的Web API 2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网络API 2建立承载令牌认证,我不知道如何(或者)承载令牌存储服务器端。下面是相关code:

启动:

 公共部分类启动
{
    公共静态OAuthAuthorizationServerOptions OAuthOptions {搞定;私人集; }
    公共静态Func键<&的UserManager LT; IdentityUser>> UserManagerFactory {搞定;组; }
    公共静态字符串PublicClientId {搞定;私人集; }    静态启动()
    {
        PublicClientId =自我;
        UserManagerFactory =()=>新的UserManager&所述; IdentityUser>(新UserStore&所述; IdentityUser>());
        OAuthOptions =新OAuthAuthorizationServerOptions
        {
            TokenEndpointPath =新PathString(/令牌),
            供应商=新ApplicationOAuthProvider(PublicClientId,UserManagerFactory)
            AuthorizeEndpointPath =新PathString(/ API /帐号/ ExternalLogin),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp =真
        };
    }    公共无效ConfigureAuth(IAppBuilder应用程序)
    {
        //使应用程序能够使用cookie来存储信息,在用户签订
        app.UseCookieAuthentication(新CookieAuthenticationOptions());        //使用cookie来临时存储有关用户记录的信息与第三方供应商登录
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

WebApiConfig:

 公共类WebApiConfig
{
    公共静态无效ConfigureWebApi()
    {
        寄存器(GlobalConfiguration.Configuration);
    }    公共静态无效的注册(HttpConfiguration HTTP)
    {
        AuthUtil.ConfigureWebApiToUseOnlyBearerTokenAuthentication(HTTP);
        http.Routes.MapHttpRoute(ActionApi,API / {控制器} / {行动},新{行动= Actions.Default});
    }
}

AuthUtil:

 公共类AuthUtil
{
    公共静态字符串令牌(字符串email)
    {
        VAR身份=新ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
        identity.AddClaim(新索赔(ClaimTypes.Name,电子邮件));
        变种票=新AuthenticationTicket(身份,新AuthenticationProperties());
        VAR currentUtc =新SystemClock()UtcNow。
        ticket.Properties.IssuedUtc = currentUtc;
        ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
        VAR令牌= Startup.OAuthOptions.AccessTokenFormat.Protect(票);
        返回记号。
    }    公共静态无效ConfigureWebApiToUseOnlyBearerTokenAuthentication(HttpConfiguration HTTP)
    {
        http.Sup pressDefaultHostAuthentication();
        http.Filters.Add(新HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    }
}

的LoginController:

 公共类的LoginController:ApiController
{
    ...    公众的Htt presponseMessage邮报([FromBody] LoginJson loginJson)
    {
        HTT presponseMessage loginResponse;
        如果(/ *是有效的登录* /)
        {
            VAR的accessToken = AuthUtil.Token(loginJson.email);
            其中的accessToken loginResponse = / * HTTP响应* /;
        }
        其他
        {
            错误loginResponse = / * HTTP响应* /;
        }
        返回loginResponse;
    }
}

使用上述code,我能够登录并存储在cookie中承载令牌的客户端,然后进行到标有[授权]控制器电话,它让我在

我的问题是:


  1. 在哪里/如何承载令牌存储服务器端?看起来这是通过调用OWIN之一hapenning,但我不能告诉在哪里。


  2. 是否有可能持续承载令牌到数据库服务器端,以便他们可以在Web API服务器重启后,留在原地?


  3. 如果答案#2没有,反正是有一个客户端,以保持其承载的令牌,并重新使用它的Web API出现故障并恢复正常后,即使?虽然这可能是在生产中罕见的,它可以很经常发生这样的本地测试。



解决方案

  1. 他们不存储服务器端 - 他们发到客户端和客户端presents他们在每次调用。他们证实,因为它们是由owin主机的保护密钥签名。在SystemWeb托管,这种保护是关键将machineKey从web.config中设置。


  2. 这是不必要的,只要保护锁owin主机的用途并不在服务器重新启动更改。


  3. 一个客户端可以守住一个令牌,只要令牌是有效的。


I am setting up bearer token authentication in Web API 2, and I don't understand how (or where) the bearer token is being stored server-side. Here is the relevant code:

Startup:

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
    public static Func<UserManager<IdentityUser>> UserManagerFactory { get; set; }
    public static string PublicClientId { get; private set; }

    static Startup()
    {
        PublicClientId = "self";
        UserManagerFactory = () => new UserManager<IdentityUser>(new UserStore<IdentityUser>());
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

    public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        // Use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

WebApiConfig:

public class WebApiConfig
{
    public static void ConfigureWebApi()
    {
        Register(GlobalConfiguration.Configuration);
    }

    public static void Register(HttpConfiguration http)
    {
        AuthUtil.ConfigureWebApiToUseOnlyBearerTokenAuthentication(http);
        http.Routes.MapHttpRoute("ActionApi", "api/{controller}/{action}", new {action = Actions.Default});
    }
}

AuthUtil:

public class AuthUtil
{
    public static string Token(string email)
    {
        var identity = new ClaimsIdentity(Startup.OAuthOptions.AuthenticationType);
        identity.AddClaim(new Claim(ClaimTypes.Name, email));
        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
        var currentUtc = new SystemClock().UtcNow;
        ticket.Properties.IssuedUtc = currentUtc;
        ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
        var token = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
        return token;
    }

    public static void ConfigureWebApiToUseOnlyBearerTokenAuthentication(HttpConfiguration http)
    {
        http.SuppressDefaultHostAuthentication();
        http.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
    }
}

LoginController:

public class LoginController : ApiController
{
    ...

    public HttpResponseMessage Post([FromBody] LoginJson loginJson)
    {
        HttpResponseMessage loginResponse;
        if (/* is valid login */)
        {
            var accessToken = AuthUtil.Token(loginJson.email);
            loginResponse = /* HTTP response including accessToken */;
        }
        else
        {
            loginResponse = /* HTTP response with error */;
        }
        return loginResponse;
    }
}

Using the above code, I'm able to login and store the bearer token client-side in a cookie, and then make calls to controllers marked with [Authorize] and it lets me in.

My questions are:

  1. Where / how is the bearer token being stored server-side? It seems like this is hapenning through one of the OWIN calls but I can't tell where.

  2. Is it possible to persist the bearer tokens to a database server-side so that they can remain in place after a Web API server restart?

  3. If the answer to #2 is no, is there anyway for a client to maintain its bearer token and re-use it even after the Web API goes down and comes back up? While this may be rare in Production, it can happen quite often doing local testing.

解决方案

  1. They're not stored server side -- they're issued to the client and the client presents them on each call. They're verified because they're signed by the owin host's protection key. In SystemWeb hosting, that protection key is the machineKey setting from web.config.

  2. That's unnecessary, as long as the protection key the owin host uses doesn't change across server restarts.

  3. A client can hold onto a token for as long as the token is valid.

这篇关于承载令牌如何存储在服务器端的Web API 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆