我有一个MVC网站,其中使用了表单身份验证,并且身份存储在会话中 . 我们修改了帐户控制器(LogOn方法)代码并删除了会话并使用Owin进行身份验证 .

Request.GetOwinContext().Authentication.SignIn(properties, claimsIdentity)

在启动时,它正在使用CookieAuthentication .

这适用于后续请求,因为令牌存储在cookie中 .

我们还需要将此令牌作为承载(或在自定义标头中)发送,以便api可以对请求进行身份验证 . 由于API托管在不同的服务器上,因此我们为MVC和WebAPI设置了相同的机器密钥 .

但是,这不起作用 . 有没有更好的方法来解密令牌并获得索赔详情?或者无缝验证令牌并在验证时允许请求 .

Web初创公司

app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = Auth_type,
            LoginPath = new PathString("/home/about"),
            LogoutPath = new PathString("/home/index"),
            SlidingExpiration = true,
            CookieSecure = CookieSecureOption.Never,
            CookieHttpOnly = false
        });

首页/关于

if (!Request.GetOwinContext().Authentication.User.Identity.IsAuthenticated)
        {
            var id = GetId() as MyIdentity;
            var prop = Getprop();
            Request.GetOwinContext().Authentication.SignIn(prop, id);
        }

Api初创公司

var OAuthOptions = new OAuthBearerAuthenticationOptions
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
                AuthenticationType = OAuthDefaults.AuthenticationType,
            };
            app.UseOAuthBearerAuthentication(OAuthOptions);

API授权属性

public class MyAuthorizeAttribute: AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            // check identity here
            base.OnAuthorization(actionContext);
        }
    }

JS调用API

var token = getCookie(".AspNet.ApplicationCookie");
                $.ajax({
                    type: "GET",
                    beforeSend: function (request) {
                        request.setRequestHeader("Authorization", "Bearer " + token);
                    },
                    url: "http://localhost:1231/authapi/api/values/get?id=1",

                    success: function (msg) {
                        alert("Success" + msg)
                    },
                    error: function (d) {
                        debugger;
                        alert("Error" + d.responseText)
                    }

                });