【问题标题】:what function does OWIN exactly use to generate a token; Can it be leveraged?OWIN 究竟使用什么函数来生成令牌;可以杠杆吗?
【发布时间】:2017-01-22 22:27:06
【问题描述】:

我可以看到使用以下代码生成令牌的方法 如

中所述

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
    AllowInsecureHttp = true,
    TokenEndpointPath = new PathString("/token"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
    Provider = new SimpleAuthorizationServerProvider()
};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);

var bearerAuth = new OAuthBearerAuthenticationOptions()
{
    Provider = new OAuthBearerAuthenticationProvider()
};

app.UseOAuthBearerAuthentication(bearerAuth);


public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{


    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        var manager = new UserManager<User, long>(new UserStore(new UserRepository()));
        var user = await manager.FindAsync(context.UserName, context.Password);

        if (user == null)
        {
            context.SetError("invalid_grant", "The user name or password is incorrect.");
        }
        else
        {
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("name",user.Email));
            context.Validated(identity);
        }


    }
}

作为消费者,我使用我的凭据向 http://localhost:9000/token 进行 REST 调用,magically 获取访问令牌

我希望能够利用该令牌生成功能在其他场景中使用来手动创建一个对**this particular** OWIN 服务器有效的令牌。

其次,是否可以有多个授权提供程序可供此服务器有条件地使用。如果是这样,如果不从头开始实现令牌生成器(如外部登录的东西),如何做到这一点?

【问题讨论】:

    标签: c# oauth asp.net-web-api2 token owin


    【解决方案1】:

    对于它的价值,我们是这样做的:

            var options = new OAuthAuthorizationServerOptions();
            var ticket = new AuthenticationTicket(...);
    
            var tokenContext = new AuthenticationTokenCreateContext(null, options.AccessTokenFormat, ticket);
            await context.options.AccessTokenProvider.CreateAsync(tokenContext);
            var token = tokenContext.Token;
            if (string.IsNullOrEmpty(token)) token = tokenContext.SerializeTicket();
            return token;
    

    options 必须是来自 app.UseOAuthAuthorizationServer(options) 调用的 OAuthAuthorizationServerOptions。

    这主要复制了 OAuthAuthorizationServerHandler 生成承载令牌的方式。 AspNetKatana/OAuthAuthorizationServerHandler.cs

    【讨论】:

      【解决方案2】:

      您可以see the code here。可能很难遵循。使其遵循 OAuth 规范并可插入(例如,您可以换出令牌格式)有很多事情要做,但最终默认配置是在幕后执行类似的操作来生成令牌:

         var ticket = new AuthenticationTicket(new ClaimsIdentity(new GenericIdentity("bob")), new AuthenticationProperties());
         IDataProtector dataProtecter = null;
         var format = new TicketDataFormat(dataProtecter);
         var accessToken = format.Protect(ticket);
      

      通常您不应该对其进行过多自定义或生成带外令牌,除非您了解安全隐患并确定开箱即用的代码是不够的。如果内置的东西不能满足您的需要,请考虑使用 Identity Server 之类的东西。

      【讨论】:

        【解决方案3】:

        OWIN 指南http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server 有以下方法生成令牌.....

        private readonly ConcurrentDictionary<string, string> _authenticationCodes =
             new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
        
         private void CreateAuthenticationCode(AuthenticationTokenCreateContext context)
         {
             context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
             _authenticationCodes[context.Token] = context.SerializeTicket();
         }
        
         private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context)
         {
             string value;
             if (_authenticationCodes.TryRemove(context.Token, out value))
             {
                 context.DeserializeTicket(value);
             }
         }
        

        这是一种方式,但我仍然不知道这是否是 MS 实现它的官方方式。很高兴知道是否有内置函数可以做到这一点。

        【讨论】:

        • 注意:GUID 不是加密安全
        • 谢谢你,我在犹豫是否要使用它,即使它在 MS 官方指南上。你知道有什么更好的方法吗?
        • 请注意,此代码不会在“SetToken”上生成访问令牌。它正在生成用于 OAuth 授权代码授权类型的代码。 tools.ietf.org/html/rfc6749#section-4.1
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-18
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多