ASP.NET : how to get an external application to write an authentication cookie?

I have an ASP.NET application that I’m transitioning from the old Membership system to Identity framework (with a view to eventually port the whole thing to .NET Core, but that’s a long way off).

I also have another .NET framework console application (it actually runs as a Windows service, but that’s neither here nor there) that basically does some offline processing of jobs that it pulls off a queue in a database table and signals back to the ASP.NET app via Signal R.

Sometimes, the console app uses Selenium to render something in the ASP.NET app and take a screenshot of it. Sometimes when it does that, it is important that the chrome driver instance running via Selenium is logged in.

Now, since the console app doesn’t have the user’s password, it can’t log in via the usual API login function that requires a username and a password. So with the old membership system, I just had the console write an auth cookie that would match the one that the ASP.NET app would write. This required making sure that the system.web section of the console app’s app.config matched the ASP.NET app’s web.config, so same machinekey and most importantly the same compatibilityMode (which tripped me up for a long time).

I had both the ASP.NET and the console app calling this shared code:

public static HttpCookie CreateAuthenticationTicket(IUserModel user, bool persist)            
{
    if (user == null)
    {
        throw new InvalidOperationException("Cannot write authentication cookie - no user");
    }

    string userData = Newtonsoft.Json.JsonConvert.SerializeObject(user);

    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        1, user.Email, DateTime.Now, persist ? DateTime.Now.AddMonths(6) : DateTime.Now.AddHours(1), persist, userData);     // 1 Yr if "remember me", 1 hour if not.

    string encrypted = FormsAuthentication.Encrypt(ticket);
    HttpCookie c = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);

    if (persist)
    {
        c.Expires = ticket.Expiration;
    }

    if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain))
    {
        c.Domain = FormsAuthentication.CookieDomain;
    }

    return c;
}

And then in the console app, before calling whatever Javascript method I need via Selenium, I set the cookie in Selenium. This all worked fine.

But I’m not sure how to pull off the same when using Identity. I’m not sure where the cookie is getting written and what it’s using for encoding. Basically, I need to be able to write an Identity compatible cookie in the console app.

As an alternative, the ASP.NET app also allows using Bearer tokens, but I’m not having much luck figuring out how to get both apps to write compatible tokens either.

This is the setup on the ASP.NET side:

public void ConfigureOAuth(IAppBuilder app, System.Web.Mvc.IDependencyResolver kernel)
{
    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
    {
        AllowInsecureHttp = true,               
        TokenEndpointPath = new PathString("/token"),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
        Provider = new SimpleAuthorizationServerProvider(kernel.GetService<UserManager<IUserModel, int>>()),
    };

    // Token Generation
    app.UseOAuthAuthorizationServer(OAuthServerOptions);
    var bearerOptions = new OAuthBearerAuthenticationOptions();
    app.UseOAuthBearerAuthentication(bearerOptions);

    app.CreatePerOwinContext<CeaApplicationUserManager>((option, context) =>
    {
        return kernel.GetService<CeaApplicationUserManager>();
    });

    app.CreatePerOwinContext<CEASignInManager>((option, context) =>
    {
        return kernel.GetService<CEASignInManager> ();
    });
    
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = PathString.Empty, 
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<CeaApplicationUserManager, IUserModel, int>(
                TimeSpan.FromMinutes(30),
                (manager, user) => manager.GenerateUserIdentityAsync(user),
                (claim) => claim.GetUserId<int>())
        },
        CookieDomain = FormsAuthentication.CookieDomain,
        CookiePath = "/; sameSite=None; secure"
    });
}

On the ASP.NET side, I can do something like this to manually produce a token:

var token = oAuthOptions.AccessTokenFormat.Protect(ticket);

Where oAuthOptions is the same OAuthBearerAuthenticationOptions that was used in the start up (which is just a new OAuthBearerAuthenticationOptions). If I try the same in the console app, the OAuthBearerAuthenticationOptions.AccessTokenFormat is null.

Clearly somewhere in creating and registering the SimpleAuthorizationServerProvider, it must get assigned, but I don’t know where and I don’t know how to give my console app a suitable instance. Or what application/machine settings it is using to encrypt the bearer token.

Any suggestions, or other approaches, are welcome.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật