简体   繁体   English

如何手动设置登录的身份用户?

[英]How do you manually set a logged in Identity User?

I am using ASP.NET Identity with an ADFS server. 我正在使用ASP.NET身份与ADFS服务器。 For development purposes, I want to avoid using the ADFS server when I'm in a network environment where I can't reach the ADFS server. 出于开发目的,我想避免在我无法访问ADFS服务器的网络环境中使用ADFS服务器。 That's why I added a simple controller action in my HomeController that manually sets the currently logged in user: 这就是为什么我在我的HomeController中添加了一个简单的控制器动作,它手动设置当前登录的用户:

#if DEBUG
    [AllowAnonymous]
    public ActionResult LogIn()
    {
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.NameIdentifier, "tester"));

        System.Web.HttpContext.Current.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
        System.Threading.Thread.CurrentPrincipal = System.Web.HttpContext.Current.User;

        return Redirect("Home/Index");
    }
#endif

And the Owin Configuration method: 和Owin配置方法:

public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions() { });

        app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                Wtrealm = realm,
                MetadataAddress = adfsMetadata
            });
    }

Commenting out the part where I use WsFederation Authentication is no problem, that way there is no link to my current ADFS server. 注释掉我使用WsFederation身份验证的部分没有问题,这样就没有链接到我当前的ADFS服务器。

The problem: When I'm redirected to the Home/Index action (that has the Authorize attribute), ASP.NET Identity doesn't recognize my ClaimsPrincipal as a valid login, so I'm redirected to the Home/Login action, which creates a loop between Home/Login and Home/Index constantly. 问题:当我被重定向到Home / Index操作(具有Authorize属性)时,ASP.NET Identity无法将我的ClaimsPrincipal识别为有效登录,因此我被重定向到Home / Login操作,在Home / Login和Home / Index之间不断创建一个循环。

My question: how do I make ASP.NET accept the ClaimsPrincipal created above as a valid login? 我的问题:如何让ASP.NET接受上面创建的ClaimsPrincipal作为有效登录?

Problem with you approach - the cookie is not set, so the user information is not preserved across the HTTP requests. 您遇到问题 - 未设置cookie,因此不会在HTTP请求中保留用户信息。 Your approach works only within a single call (there are uses for that, but not for you) 您的方法仅适用于一次调用(有用途,但不适用于您)

You can still use IAuthenticationManager from OWIN to set the cookie: 您仍然可以使用OWIN的IAuthenticationManager来设置cookie:

#if DEBUG
    [AllowAnonymous]
    public ActionResult LogIn()
    {
        var identity = new ClaimsIdentity("ApplicationCookie", ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType);
        identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Active Directory"));
        identity.AddClaim(new Claim(ClaimTypes.Name, "Testy McTestface"));
        identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, "testUser"));

        IAuthenticationManager authenticationManager = HttpContext.GetOwinContext().Authentication;
        authenticationManager.SignOut("ApplicationCookie");
        authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);

        return Redirect("Home/Index");
    }
#endif

You will need nuget packages Microsoft.Owin.Security.Cookies , Microsoft.Owin.Host.SystemWeb . 您将需要nuget包Microsoft.Owin.Security.CookiesMicrosoft.Owin.Host.SystemWeb See more explanations in my blog-post about authentication with AD 在我的博客文章中查看有关AD身份验证的更多解释

You will also need to make sure CookieAuthenticationMiddleware is configured correclty: 您还需要确保CookieAuthenticationMiddleware配置为correclty:

 public void Configuration(IAppBuilder app)
    {
        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = "ApplicationCookie",
            LoginPath = new PathString("/Home/Login"),
            Provider = new CookieAuthenticationProvider(),
            CookieName = "ApplicationCookie",
            CookieHttpOnly = true,
            ExpireTimeSpan = TimeSpan.FromHours(1),
        });

        app.UseWsFederationAuthentication(
            new WsFederationAuthenticationOptions
            {
                Wtrealm = realm,
                MetadataAddress = adfsMetadata
            });
    }

Especially pay authentication to AuthenticationType value - it must match the value in ClaimsIdentity constructor. 特别是对AuthenticationType值进行AuthenticationType - 它必须与ClaimsIdentity构造函数中的值匹配。 Otherwise cookie will not be set, or you won't be able to log-out. 否则将不会设置cookie,否则您将无法注销。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何手动设置 HttpContext.User.Identity.IsAuthenticated 的值 - How to manually set value of HttpContext.User.Identity.IsAuthenticated 您如何获得用户身份? - How do you get a User Identity? 如何将IIS应用程序池标识用户区域设置为ApplicationPoolIdentity时,如何设置它 - How do you set the IIS Application Pool Identity User Locale when it's set to ApplicationPoolIdentity Identity Server 4 - 如何检查用户是否登录 - Identity Server 4 - how to check if user is logged in 您如何使用User.Identity.GetUserId(); - How do you use User.Identity.GetUserId(); 你如何设置ApiController.User - How do you set ApiController.User 如何在当前用户的ASP.NET Identity 2中获取用户配置文件值? - How do you obtain user profile values in ASP.NET Identity 2 of current user? ASP.NET身份-如何仅允许访问已登录的用户? - ASP.NET Identity - How to allow access to ONLY the logged in User? ASP.NET身份-如何维护登录用户角色? - Asp.net identity - How to maintain logged in user role? 即使用户已登录,httpcontext 也会将用户身份返回为 null,尝试为 hangfire 设置身份验证过滤器 - httpcontext returns user identity as null even if user is logged in, trying to set authenticationfilter for hangfire
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM