3

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

4

1 回答 1

5
  1. OWIN ServerMiddleware 默认的 Tiken 数据保护方式是使用DPAPI(Data Protection API)
  2. 为了在服务器端撤销令牌,需要实现令牌存储。您可以AccessTokenProvider.Create用来创建和存储 Token。

这是这种情况的示例。以此为例代码片段。

在 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"))
        });
    }

提供加密:这是基于 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());
        }
    }

令牌提供者

    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);
        }
    }
于 2013-10-24T12:55:20.770 回答