使用ASP.net API进行承载令牌认证

Aar*_*her 3 oauth asp.net-web-api owin

我正在研究使用ASP.net Web API来设置带有承载令牌的请求身份验证.当您使用OWIN服务器中间件时,加密密钥来自哪里?服务器如何撤销尚未过期的令牌?

jd4*_*d4u 5

  1. OWIN ServerMiddleware的默认Tiken数据保护方法是使用DPAPI(数据保护API)
  2. 对于在服务器端撤销令牌,需要实现令牌存储.您可以使用它AccessTokenProvider.Create来创建和存储令牌.

以下是此类方案的示例.以此为例,代码片段.

在Startup.cs中注册

 app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
        {
            AuthorizeEndpointPath = new PathString("/Authorize"),
            TokenEndpointPath = new PathString("/Token"),
            ApplicationCanDisplayErrors = true,
            Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
            AuthorizationCodeProvider = new MyAuthenticationTokenProvider(TokenType.Code),
            AccessTokenProvider = new MyAuthenticationTokenProvider(TokenType.Access),
            RefreshTokenProvider = new MyAuthenticationTokenProvider(TokenType.Refresh),
            AuthorizationCodeFormat = new MyFormatProvider("MyAudiences"),
            AccessTokenFormat = new MyFormatProvider("MyAudiences"),
            RefreshTokenFormat = new MyFormatProvider("MyAudiences"))
        });
    }
Run Code Online (Sandbox Code Playgroud)

提供加密:这是基于Katana项目中的JwtFormat.仍然不支持JwtFormat.protect()方法.所以你需要创建自己的实现.

    //You need to manage your Key in this class
    public class MyFormatProvider: ISecureDataFormat<AuthenticationTicket>
    {
        public MyFormatProvider(string allowedAudiences)
        {
        }
        public string Protect(AuthenticationTicket data)
        {
            return "encrypted";
        }
        public AuthenticationTicket Unprotect(string protectedText)
        {
            return new AuthenticationTicket(new System.Security.Claims.ClaimsIdentity(), new AuthenticationProperties());
        }
    }
Run Code Online (Sandbox Code Playgroud)

令牌提供者

    public enum TokenType { Code,Access,Refresh }
    public class MyAuthenticationTokenProvider : AuthenticationTokenProvider
    {
        TokenType tokenType = TokenType.Access;
        public MyAuthenticationTokenProvider(TokenType tokenType)
        {

        }
        public override void Create(AuthenticationTokenCreateContext context)
        {
            /*Create Token, Store Token and Tiket info*/
            context.SetToken("MyToken");/*This will call Your MyFormatProvider internally*/
            base.Create(context);
        }

        public override void Receive(AuthenticationTokenReceiveContext context)
        {
            /*retrieve Token and Tiket info to process*/
            base.Receive(context);
        }
    }
Run Code Online (Sandbox Code Playgroud)