当前位置: 首页>>代码示例>>C#>>正文


C# IRequest.GetBearerToken方法代码示例

本文整理汇总了C#中IRequest.GetBearerToken方法的典型用法代码示例。如果您正苦于以下问题:C# IRequest.GetBearerToken方法的具体用法?C# IRequest.GetBearerToken怎么用?C# IRequest.GetBearerToken使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在IRequest的用法示例。


在下文中一共展示了IRequest.GetBearerToken方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: PreAuthenticate

        public void PreAuthenticate(IRequest req, IResponse res)
        {
            if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName))
                return;

            var bearerToken = req.GetBearerToken()
                ?? req.GetCookieValue(Keywords.TokenCookie);

            if (bearerToken != null)
            {
                var parts = bearerToken.Split('.');
                if (parts.Length == 3)
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);

                    var header = parts[0];
                    var payload = parts[1];
                    var signatureBytes = parts[2].FromBase64UrlSafe();

                    var headerJson = header.FromBase64UrlSafe().FromUtf8Bytes();
                    var payloadBytes = payload.FromBase64UrlSafe();

                    var headerData = headerJson.FromJson<Dictionary<string, string>>();

                    var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes();

                    var algorithm = headerData["alg"];

                    //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
                    if (RequireHashAlgorithm && algorithm != HashAlgorithm)
                        throw new NotSupportedException("Invalid algoritm '{0}', expected '{1}'".Fmt(algorithm, HashAlgorithm));

                    if (!VerifyPayload(algorithm, bytesToSign, signatureBytes))
                        return;

                    var payloadJson = payloadBytes.FromUtf8Bytes();
                    var jwtPayload = JsonObject.Parse(payloadJson);

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
                else if (parts.Length == 5) //Encrypted JWE Token
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);

                    if (PrivateKey == null || PublicKey == null)
                        throw new NotSupportedException("PrivateKey is required to DecryptPayload");

                    var jweHeaderBase64Url = parts[0];
                    var jweEncKeyBase64Url = parts[1];
                    var ivBase64Url = parts[2];
                    var cipherTextBase64Url = parts[3];
                    var tagBase64Url = parts[4];

                    var sentTag = tagBase64Url.FromBase64UrlSafe();
                    var aadBytes = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                    var iv = ivBase64Url.FromBase64UrlSafe();
                    var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                    var jweEncKey = jweEncKeyBase64Url.FromBase64UrlSafe();
                    var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                    var authKey = new byte[128 / 8];
                    var cryptKey = new byte[128 / 8];
                    Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                    Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                    using (var hmac = new HMACSHA256(authKey))
                    using (var encryptedStream = new MemoryStream())
                    {
                        using (var writer = new BinaryWriter(encryptedStream))
                        {
                            writer.Write(aadBytes);
                            writer.Write(iv);
                            writer.Write(cipherText);
                            writer.Flush();

                            var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                            if (!calcTag.EquivalentTo(sentTag))
                                return;
                        }
                    }

                    JsonObject jwtPayload;
                    var aes = Aes.Create();
                    aes.KeySize = 128;
                    aes.BlockSize = 128;
                    aes.Mode = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;
                    using (aes)
                    using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                    using (var ms = MemoryStreamFactory.GetStream(cipherText))
                    using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        var jwtPayloadBytes = cryptStream.ReadFully();
                        jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes());
                    }
//.........这里部分代码省略.........
开发者ID:AVee,项目名称:ServiceStack,代码行数:101,代码来源:JwtAuthProviderReader.cs

示例2: PreAuthenticate

        public void PreAuthenticate(IRequest req, IResponse res)
        {
            //The API Key is sent in the Basic Auth Username and Password is Empty
            var userPass = req.GetBasicAuthUserAndPassword();
            if (userPass != null && string.IsNullOrEmpty(userPass.Value.Value))
            {
                if (RequireSecureConnection && !req.IsSecureConnection)
                    throw HttpError.Forbidden(ErrorMessages.ApiKeyRequiresSecureConnection);

                var apiKey = userPass.Value.Key;

                PreAuthenticateWithApiKey(req, res, apiKey);
            }
            var bearerToken = req.GetBearerToken();
            if (bearerToken != null)
            {
                var authRepo = (IManageApiKeys)HostContext.AppHost.GetAuthRepository(req);
                using (authRepo as IDisposable)
                {
                    if (authRepo.ApiKeyExists(bearerToken))
                    {
                        if (RequireSecureConnection && !req.IsSecureConnection)
                            throw HttpError.Forbidden(ErrorMessages.ApiKeyRequiresSecureConnection);

                        PreAuthenticateWithApiKey(req, res, bearerToken);
                    }
                }
            }
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:29,代码来源:ApiKeyAuthProvider.cs

示例3: PreAuthenticate

 public void PreAuthenticate(IRequest req, IResponse res)
 {
     //The API Key is sent in the Basic Auth Username and Password is Empty
     var userPass = req.GetBasicAuthUserAndPassword();
     if (userPass != null && string.IsNullOrEmpty(userPass.Value.Value))
     {
         var apiKey = GetApiKey(req, userPass.Value.Key);
         PreAuthenticateWithApiKey(req, res, apiKey);
     }
     var bearerToken = req.GetBearerToken();
     if (bearerToken != null)
     {
         var apiKey = GetApiKey(req, bearerToken);
         if (apiKey != null)
         {
             PreAuthenticateWithApiKey(req, res, apiKey);
         }
     }
 }
开发者ID:ServiceStack,项目名称:ServiceStack,代码行数:19,代码来源:ApiKeyAuthProvider.cs


注:本文中的IRequest.GetBearerToken方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。