MVC5应用程序中的.AspNetCore.Bearer cookie解密问题

时间:2019-07-09 09:17:50

标签: asp.net-mvc authentication asp.net-core encryption cookies

我在Cookie解密方面遇到问题,该问题是在ASP .NET Core应用程序登录期间创建的,并在声明中包含Json Web令牌。 我想从MVC5(.NET Framework 4.5.2)中开发的应用程序解密cookie,并使用JWT获得一些值。不幸的是,我收到一个错误“密码操作期间发生错误。”

我已经尝试过以某种方式对其进行解密,但始终会收到此错误。代码如下:

在核心应用中登录代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GoogleMobileAds.Api;

public class AdsManager : MonoBehaviour
{
    public static AdsManager instance;

    private string appID = "ca-app-pub-3940256099942544~3347511713";

    private BannerView bannerView;
    private string bannerID = "ca-app-pub-3940256099942544/6300978111";

    private InterstitialAd fullScreenAd;
    private string fullScreenAdID = "ca-app-pub-3940256099942544/1033173712";

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            Destroy(this);
        }
    }

    private void Start()
    {
        RequestFullScreenAd();
    }

    public void RequestBanner()
    {
        bannerView = new BannerView(bannerID, AdSize.Banner, AdPosition.Bottom);

        AdRequest request = new AdRequest.Builder().Build();

        bannerView.LoadAd(request);

        bannerView.Show();
    }

    public void HideBanner()
    {
        bannerView.Hide();
    }

    public void RequestFullScreenAd()
    {

        fullScreenAd = new InterstitialAd(fullScreenAd);

        AdRequest request = new AdRequest.Builder().Build();

        fullScreenAd.LoadAd(request);

    }

    public void ShowFullScreenAd()
    {
        if (fullScreenAd.IsLoaded())
        {
            fullScreenAd.Show();
        }
        else
        {
            Debug.Log("Full Screen Ad Not Loaded");
        }
    }

}

.NET Framework中间件中的解密:

        public async Task<bool> LoginAsync(LoginDto loginDto)
        {
            await LogoutAsync();

            var tokenHandler = new JwtSecurityTokenHandler();
            var settings = _jwtSettingsFactory.CreateTokenValidationParameters();

            // Retrieve principal from JWT
            var jwtToken = await _accountService.Login(loginDto);
            var principal = tokenHandler.ValidateToken(jwtToken.Token, settings, out var validatedToken);

            // Cast needed for accessing claims property
            var identity = principal.Identity as ClaimsIdentity;

            // parse jwt token to get all claims
            var securityToken = tokenHandler.ReadToken(jwtToken.Token) as JwtSecurityToken;

            var extraClaims = securityToken.Claims.Where(c => !identity.Claims.Any(x => x.Type == c.Type)).ToList();
            extraClaims.Add(new Claim("jwt", jwtToken.Token));
            identity.AddClaims(extraClaims);

            var authenticationProperties = new AuthenticationProperties()
            {
                IssuedUtc = Convert.ToInt64(identity.Claims.Single(c => c.Type == JwtRegisteredClaimNames.Iat).Value).ToUnixEpochDate(),
                ExpiresUtc = Convert.ToInt64(identity.Claims.Single(c => c.Type == JwtRegisteredClaimNames.Exp).Value).ToUnixEpochDate(),
                IsPersistent = true
            };

            await _httpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, principal, authenticationProperties);

            return identity.IsAuthenticated;
        }

第一次尝试:

        public class MachineKeyProtector : IDataProtector
        {
            private string[] _cookiePurpose = {
                typeof(CookieAuthenticationMiddleware).FullName,
                "Bearer",
                "v2"
            };

            public byte[] Protect(byte[] userData)
            {
                return System.Web.Security.MachineKey.Protect(userData, _cookiePurpose);
            }

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

第二次尝试:

            var cookie = context.Request.Cookies.Get(".AspNetCore.Bearer");
            var ticket = cookie.Value;
            UTF8Encoding specialUtf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
            var encoder = new Base64UrlTextEncoder();
            byte[] protectedBytes = encoder.Decode(ticket);
            var dataProtector = new MachineKeyProtector();
            var plainBytes = dataProtector.Unprotect(protectedBytes);
            string plainText = specialUtf8Encoding.GetString(plainBytes);

有人知道我在做什么错吗,或者知道有更好的解密Cookie的方法吗?

0 个答案:

没有答案