Decrypting OWIN Authentication Ticket

参考:https://long2know.com/2015/05/decrypting-owin-authentication-ticket/

AuthServer产生的Token因为没有制定自定义的加密逻辑,所以会使用默认的加密算法,故只能被AuthServer自身解密。
所以下列代码必须写在AuthServer项目内部才能使用。

using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.OAuth;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Web.Http;
using System.Web.Http.Results;
using System.IdentityModel.Tokens;
using Microsoft.Owin.Security.Jwt;

namespace DIH.Core.AuthServer.IIS
{
    [RoutePrefix("api/my")]
    public class MyController : ApiController
    {
        public MyController()
        {
        }

        [Route("", Name = "DecryptToken")]
        [HttpPost]
        public IHttpActionResult DecryptToken([FromBody]string token)
        {
            token = "3l4Bg-xYshdFlaD4In_RZLoDUyx-BcMyVafx97WMPrm59hyQzovjbANjCQ6Yaz6C9OnYSoGy5WvrB79lKdncUIEcxACFrdTGFzTlyTqPOrwm7HwpCa-zTPVnk3jBgq72joub58FPKxQozdyN0JqvIgB6MyRX9GfVukS2tGQltEQHCJGJDmRYfcUo0l4YTgomA9zYWIE_ERryYkeXL1zN0WKHX_QrYTADRaPKcniZ-iMoZ7v9i5vSV_GFGdDJ4BYS";
               var secureDataFormat = new TicketDataFormat(new MachineKeyProtector());
            AuthenticationTicket ticket = secureDataFormat.Unprotect(token);


            string AuthenticationType = ticket.Identity.AuthenticationType;
            List<Claim> lstClaim = ticket.Identity.Claims.Select(claim => claim).ToList();

            var a = new Microsoft.Owin.Security.Jwt.JwtFormat(new TokenValidationParameters()
            {

            });
            string jwt = a.Protect(ticket);

            return Ok(jwt);
        }
    }

    /// <summary>
    /// Helper method to decrypt the OWIN ticket
    /// </summary>
    class MachineKeyProtector : IDataProtector
    {
        private readonly string[] _purpose = new string[]
        {
            typeof(OAuthAuthorizationServerMiddleware).Namespace,
            "Access_Token",
            "v1"
        };
        public byte[] Protect(byte[] userData)
        {
            //throw new NotImplementedException();
            return System.Web.Security.MachineKey.Protect(userData, _purpose);
        }

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

}

  

原文地址:https://www.cnblogs.com/Ceri/p/7670435.html