注销时如何删除AccessToken

时间:2019-08-09 15:28:10

标签: c# asp.net-mvc asp.net-web-api logout bearer-token

我正在使用Asp.net WebApi,并且使用了令牌身份验证,在上一个问题中,我设法找到了登录代码,但现在我在注销问题上遇到了问题^^“ 实际上,我控制器中的[Authorize]属性不起作用,许多人建议最好的解决方法是注销时删除访问令牌。 我知道您会告诉我,我应该使用“ ApiController”,但是如果使用它,我将无法返回视图,这就是我使用Controller的原因。

对于注销,我尝试了以下代码:

Request.GetOwinContext().Authentication.SignOut();
Request.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
System.Web.HttpContext.Current.GetOwinContext().Authentication.SignOut(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie);
FormsAuthentication.SignOut();

和这个:

var identity = (ClaimsIdentity)User.Identity;

            AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties()
            {
                ExpiresUtc = DateTime.Now.AddYears(-5)
            });
            ticket.Properties.ExpiresUtc = DateTime.Now.AddYears(-5);

            var principal = ClaimsPrincipal.Current;
            var ClientId = principal.Claims.FirstOrDefault(c => c.Type == identity.GetUserId()).Value;
            var USERNAME = principal.Claims.FirstOrDefault(c => c.Type == identity.GetUserName()).Value;

            var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions();
            oAuthAuthorizationServerOptions.AccessTokenExpireTimeSpan = TimeSpan.FromTicks(DateTime.UtcNow.AddYears(-5).Ticks);
            var con = System.Web.HttpContext.Current.GetOwinContext();
            var context = new OAuthGrantResourceOwnerCredentialsContext(con, null, ClientId, USERNAME, null, null);
            context.Validated(ticket);

但是两者均无效,并且[Authorize]属性仍然无效

这是我的控制器代码:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Windows;

namespace Cartographie.Controllers
{
    public class HomeController : Controller
    {
        string name;
        string direction;
        DateTime date_cnx;

        public ActionResult Logout()
        {
            \\searching for code that come here !!!!!
            return RedirectToAction("Login");
        }


        public ActionResult Login()
        {
            ViewBag.Title = "Login";

            return View();
        }

        [Route("/Homeadmin")]
        [Authorize(Roles = "admin")]
        [HttpGet]
        public ActionResult Homeadmin(string nom, string dir, DateTime date)
        {
            ViewBag.UserName = nom;
            ViewBag.Direction = dir;
            ViewBag.Date = date.ToShortDateString();
            return View();
        }

        [Route("/Homeagent")]
        [HttpPost]
        [Authorize(Roles = "user")]
        public ActionResult Homeuser(string nom, string dir, DateTime date)
        {
            ViewBag.UserName = nom;
            ViewBag.Direction = dir;
            ViewBag.Date = date.ToShortDateString();

            return View();
        }


        public ActionResult ControLogin(string user, string pass)
        {
            TempData["email"] = user;
            var t = JsonConvert.DeserializeObject<Token>("");
            if (user == "" || pass == "")
            {
                MessageBox.Show("FAILED", "failed");
                return RedirectToAction("Login");

            }
            else
            {

                var pairs = new List<KeyValuePair<string, string>>
                    {
                        new KeyValuePair<string, string>( "grant_type", "password" ),
                        new KeyValuePair<string, string>( "username", user),
                        new KeyValuePair<string, string> ( "Password", pass )
                    };
                var content = new FormUrlEncodedContent(pairs);

                ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
                using (var client = new HttpClient())
                {
                    var response = client.PostAsync("https://localhost:44396/" + "Token", content).Result;
                    String token = response.Content.ReadAsStringAsync().Result;

                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        t = JsonConvert.DeserializeObject<Token>(token);

                        client.DefaultRequestHeaders.Clear();
                        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
                    }

                }
                if (t.access_token == null)
                {
                    MessageBox.Show("Cet utilisateur n'existe pas", "ERREUR");
                    return RedirectToAction("Login");

                }
                else
                {
                    SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
                    try
                    {
                        con.Open();
                        SqlCommand cmd = new SqlCommand("select * from Users where email=@email", con);
                        cmd.Parameters.AddWithValue("@email", user);

                        SqlDataReader reader = cmd.ExecuteReader();

                        if (reader.Read())
                        {
                            string role = reader["role"].ToString();
                            name = reader["fullname"].ToString();
                            direction = reader["direction"].ToString();
                            int colIndex = reader.GetOrdinal("date_cnx");
                            date_cnx = reader.GetDateTime(colIndex);
                            con.Close();
                            if (role == "admin")
                                return RedirectToAction("Homeadmin", new { nom = name, dir = direction, date = date_cnx });

                            else
                                return RedirectToAction("Homeuser", new { nom = name, dir = direction, date = date_cnx });

                        }
                        else
                            return RedirectToAction("Login");

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Connection Problems, " + ex.Message.ToString());
                        return RedirectToAction("Login");
                    }
                }

            }
        }
    }
}

我要在注销时删除访问令牌,并使Attibute [Authorzie]工作

0 个答案:

没有答案