Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中手动解码OAuth承载令牌#_C#_Asp.net Web Api_Oauth 2.0_Owin_Bearer Token - Fatal编程技术网

C# 在c中手动解码OAuth承载令牌#

C# 在c中手动解码OAuth承载令牌#,c#,asp.net-web-api,oauth-2.0,owin,bearer-token,C#,Asp.net Web Api,Oauth 2.0,Owin,Bearer Token,在我基于Web Api 2.2 OWIN的应用程序中,我遇到了一种情况,我需要手动解码承载令牌,但我不知道如何做到这一点。 这是我的startup.cs public class Startup { public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; } public static UnityContainer IoC; public void Confi

在我基于Web Api 2.2 OWIN的应用程序中,我遇到了一种情况,我需要手动解码承载令牌,但我不知道如何做到这一点。 这是我的startup.cs

public class Startup
{
    public static OAuthAuthorizationServerOptions OAuthServerOptions { get; private set; }
    public static UnityContainer IoC;
    public void Configuration(IAppBuilder app)
    {
        //Set Auth configuration
        ConfigureOAuth(app);

        ....and other stuff
    }

    public void ConfigureOAuth(IAppBuilder app)
    {
        OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new AuthProvider(IoC.Resolve<IUserService>(), IoC.Resolve<IAppSettings>())
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}
公共类启动
{
公共静态OAuthAuthorizationServerOptions OAuthServerOptions{get;private set;}
公共静态单元容器IoC;
公共无效配置(IAppBuilder应用程序)
{
//设置身份验证配置
配置OAuth(应用程序);
……还有其他东西
}
公共void配置OAuth(IAppBuilder应用程序)
{
OAuthServerOptions=新的OAuthAuthorizationServerOptions()
{
AllowInsecureHttp=true,
TokenEndpointPath=新路径字符串(“/token”),
AccessTokenExpireTimeSpan=TimeSpan.FromDays(1),
Provider=新的AuthProvider(IoC.Resolve(),IoC.Resolve())
};
//令牌生成
使用OAuthAuthorizationServer(OAuthServerOptions);
使用OAuthBeareAuthentication(新的OAuthBeareAuthenticationOptions());
}
}
在我的控制器中,我发送承载令牌作为参数

[RoutePrefix("api/EP")]
public class EPController : MasterController
{
    [HttpGet]
    [AllowAnonymous]
    [Route("DC")]
    public async Task<HttpResponseMessage> GetDC(string token)
    {
        //Get the claim identity from the token here
        //Startup.OAuthServerOptions...

        //..and other stuff
    }
}
[RoutePrefix(“api/EP”)]
公共类EPController:MasterController
{
[HttpGet]
[异名]
[路线(“DC”)]
公共异步任务GetDC(字符串令牌)
{
//从此处的令牌获取索赔标识
//Startup.OAuthServerOptions。。。
//…和其他东西
}
}
如何手动解码并从作为参数传递的令牌中获取声明


注意:我知道我可以在标头中发送令牌,并使用[Authorize]和(ClaimsIdentity)User.Identity等,但问题是当令牌未显示在标头中时,如何读取令牌

您可以使用System.IdentityModel.Tokens.JWT包读取JWT并创建主体和标识对象-

下面是一个快速示例,显示了读取和验证令牌时可用的选项

    private ClaimsIdentity GetIdentityFromToken(string token, X509Certificate2 certificate)
    {  
        var tokenDecoder = new JwtSecurityTokenHandler();         
        var jwtSecurityToken = (JwtSecurityToken)tokenDecoder.ReadToken(token);

        SecurityToken validatedToken;

        var principal = tokenDecoder.ValidateToken(
            jwtSecurityToken.RawData,
            new TokenValidationParameters()
                {
                    ValidateActor = false,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                    ValidateIssuerSigningKey = false,
                    RequireExpirationTime = false,
                    RequireSignedTokens = false,
                    IssuerSigningToken = new X509SecurityToken(certificate)
                },
            out validatedToken);

        return principal.Identities.FirstOrDefault();
    }

我创建了一个反序列化承载令牌的示例项目,该令牌使用MachineKeyDataProtector进行加密。 你可以看看源代码


只需将此放置在此处,供将来可能访问的其他人使用。在中找到的解决方案更简单

只有两行:

var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
AuthenticationTicket ticket = secureDataFormat.Unprotect(accessToken);



private class MachineKeyProtector : IDataProtector {
    private readonly string[] _purpose =
    {
        typeof(OAuthAuthorizationServerMiddleware).Namespace,
        "Access_Token",
        "v1"
    };

    public byte[] Protect(byte[] userData)
    {
        throw new NotImplementedException();
    }

    public byte[] Unprotect(byte[] protectedData)
    {
        return System.Web.Security.MachineKey.Unprotect(protectedData, _purpose);
    } }

谢谢,这正是我想要的!虽然上面提到的方法可能有效。一个更简单的解决方案可以在下面找到:谢谢,你救了我一天。asp.net身份中的承载令牌不是jwt令牌。jwt令牌应该类似于:header.payload.signature。我得到的持票人代币不包含点,也不是base64编码的。尽管我还没有测试这个解决方案,但我认为你花点时间在一个封闭的问题+1上分享你的解决方案是很好的