Article

Authenticate a user programatically in Sitefinity 10+ to view a protected resource

« Go Back

Information

 
Article Number000082866
EnvironmentProduct: Sitefinity
Version: 10.x
OS: All supported OS versions
Database: All supported Microsoft SQL Server versions
Question/Problem Description
How to authenticate a user through code in order to request protected page?
How to log in via code to access protected resources, e.g. form resources?
How to work with WCF services which require authentication in versions Sitefinity 10.x or later?
 
Steps to Reproduce
Clarifying Information
The protected resources require authentication cookies to be issued.
Error Message
Defect/Enhancement Number
Cause
Resolution
The solution refers to Sitefinity 10+ approach described in Progress Article 000071678, Authenticate user in Sitefinity using a console application - call Sitefinity services server side and extends it with issuing of authentication cookie. This solution builds over it.

The solution in the above KB article uses Bearer token to authenticate requests to web services, but for pages and for working with services which require certain permissions (e.g. Users service, ManageUsers permission), a cookie must be issued on top of the Bearer token.

To construct the cookie refer to the attached AuthenticateSitefinity.zip that contains the helper class (SitefinityClient.cs) to issue a cookie. In this class refer to the constants at the bottom to fill in ClientId, ClientSecret, username, password and membership provider of the site where the authentication occurs. 
private const string ClientId = "testApp";
private const string ClientSecret = "secret";
private const string DefaultAdminName = "admin2@admin.com";
private const string DefaultAdminPass = "password";
private const string AuthorizationHeader = "Authorization";
private const string MembershipProviderParameter = "membershipProvider";
private const string IdentityServerTokenServiceUrl = "/Sitefinity/Authenticate/OpenID/connect/token";
private const string CookieAuthPath = "/retrieveAuthCookie";
private const string MembershipProvider = "Default";
In the Main method, if executed in a console application, execute the following:
 
public static void Main(string[] args)
        {
            SitefinityClient client = new SitefinityClient();
            client.RequestAuthenticate("Default", "admin@progress.com", "password", false, true, true);

            client.DefaultRequestHeaders.Add(SitefinityClient.ServiceRequestHeader, bool.TrueString);
            var responseService = client.GetAsync("Sitefinity/Services/Publishing/PublishingService.svc")
                                        .Result.Content.ReadAsStringAsync().Result;
           
            var content = new
            {
                urlname = "test-library",
                title = "test library"
            };

            var json = new javascriptserializer().serialize(content);

            var postrequest = client.postasync("api/default/documentlibraries", new stringcontent(json, encoding.utf8, "application/json"));
           var result = postrequest.result;

            client.Logout();
        }

Refer to the attached console application for a sample on using the SitefinityClient.cs to issue a cookie to view a protected page.
Workaround
Notes
If there are SEO rewrite rules enabled, e.g. as in Progress Article 000088755, SEO: Use URL rewrite in Sitefinity , the following lines should be added:
<rule name="preventRewriteRules_Special" stopProcessing="true"> 
    <match url="^/?(retrieveAuthCookie)" ignoreCase="true" /> 
    <action type="None" /> 
</rule>
With that "retrieveAuthCookie" would be not in lowercase. 

If attempting to set the cookies (a.k.a. var cookiesToSet = response.Headers.GetValues("Set-Cookie");) results in 404 'File not found' error (System.InvalidOperationException), add authCookieFromBearerTokenEndpoint="/retrieveAuthCookie" to the Authentication.config, as described in Progress Article 000084974, The path must start with a '/' followed by one or more characters on startup

__________
More information on how the CookieEndpoint works and why it is always returning status of 200
Progress Article 000093717 RetrieveCookie Endpoint always returning 200
Last Modified Date1/9/2019 1:07 PM


Feedback
 
Did this article resolve your question/issue?

   

Your feedback is appreciated.

Please tell us how we can make this article more useful. Please provide us a way to contact you, should we need clarification on the feedback provided or if you need further assistance.

Characters Remaining: 1025