UFO ET IT

Bearer 토큰은 Web API 2에서 서버 측에 어떻게 저장됩니까?

ufoet 2020. 12. 12. 11:53
반응형

Bearer 토큰은 Web API 2에서 서버 측에 어떻게 저장됩니까?


Web API 2에서 전달자 토큰 인증을 설정하고 있는데 전달자 토큰이 서버 측에 저장되는 방법 (또는 위치)을 이해할 수 없습니다. 다음은 관련 코드입니다.

시작 :

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

위의 코드를 사용하여 클라이언트 측에 로그인하여 쿠키에 베어러 토큰을 저장 한 다음 [Authorize]로 표시된 컨트롤러를 호출 할 수 있습니다.

내 질문은 다음과 같습니다.

  1. Bearer 토큰은 어디에 / 어떻게 서버 측에 저장됩니까? 이것이 OWIN 호출 중 하나를 통해 발생하는 것처럼 보이지만 어디인지 알 수 없습니다.

  2. Bearer 토큰을 데이터베이스 서버 측에 유지하여 Web API 서버가 다시 시작된 후에도 그대로 유지 될 수 있습니까?

  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.


For those who are looking for how to set web.config, here is a sample

<system.web>
<machineKey validation="HMACSHA256" validationKey="64-hex"
                 decryption="AES" decryptionKey="another-64-hex"/>
</system.web>

You need both validationKey and decriptionkey to make it work.

And here is how to generate keys https://msdn.microsoft.com/en-us/library/ms998288.aspx


To add to this, the token can be persisted server side using the SessionStore property of of CookieAuthenticationOptions. I wouldn't advocate doing this but it's there if your tokens become excessively large.

This is an IAuthenticationSessionStore so you could implement your own storage medium.


By default the token is not stored by the server. Only your client has it and is sending it through the authorization header to the server.

If you used the default template provided by Visual Studio, in the Startup ConfigureAuth method the following IAppBuilder extension is called: app.UseOAuthBearerTokens(OAuthOptions).

참고URL : https://stackoverflow.com/questions/21102252/how-are-bearer-tokens-stored-server-side-in-web-api-2

반응형