簡體   English   中英

如何檢查用戶是否在MVC中通過了身份驗證

[英]How to check if a user is authenticated in MVC

通過遵循此示例 ,我已經完成了自定義身份驗證系統,並且它可以工作。 我的代碼如下。 我想知道如何控制用戶是否在其他操作中通過了身份驗證,可以說用戶是否轉到/ Profile / Index?

我嘗試了HttpContext.User和User.Identity,但是沒有用。

[HttpPost]
public ActionResult Login(string username, string password)
{
    if (new UserManager().IsValid(username, password))
    {
        var ident = new ClaimsIdentity(
          new[] {
      new Claim(ClaimTypes.NameIdentifier, username),
      new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
      new Claim(ClaimTypes.Name,username)
          },
          DefaultAuthenticationTypes.ApplicationCookie);

        HttpContext.GetOwinContext().Authentication.SignIn(
           new AuthenticationProperties { IsPersistent = false }, ident);
        return RedirectToAction("MyAction"); // auth succeed 
    }
    ModelState.AddModelError("", "invalid username or password");
    return View();
}

這是我的Global.asax

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

您沒有在Owin管道中設置身份驗證。 最簡單的方法是添加一個類似於以下文件的文件。 將其App_StartIdentityConfig.cs並將其放在App_Start文件夾中:

using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Owin;

//This line tells Owin which method to call
[assembly: OwinStartup(typeof(TokenBasedAuthenticationSample.IdentityConfig))]
namespace TokenBasedAuthenticationSample
{
    public class IdentityConfig
    {
        public void Configuration(IAppBuilder app)
        {
            //Here we add cookie authentication middleware to the pipeline 
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/login"),
            });
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM