缺少什么功能才能生成令牌;它可以被杠杆化吗?

问题描述 投票:2回答:3

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

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
3个回答
1
投票

你可以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这样的东西。


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;

选项必须是app.UseOAuthAuthorizationServer(options)调用中的OAuthAuthorizationServerOptions。

这主要是复制OAuthAuthorizationServerHandler如何生成承载令牌。 AspNetKatana/OAuthAuthorizationServerHandler.cs


0
投票

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实现它的官方方式。很高兴知道是否有内置函数可以做到这一点。

© www.soinside.com 2019 - 2024. All rights reserved.