C # Webservice authentication problem between two web applications

I am working on a web application that runs in a company. This web application should make a call to the service, which is part of the second web application.

In a central web application, I have this piece of code;

var clientUri = "http://website.localhost/Services/Info.svc/account";
var uri = new Uri(clientUri);
var networkCredentials = new NetworkCredential(_configuration.ServiceUserName, _configuration.ServicePassword);
var httpClient = new HttpClient();

httpClient.DefaultHeaders.Authorization = Credential.CreateBasic(_configuration.ServiceUserName,                                                                                   _configuration.ServicePassword);
httpClient.TransportSettings.PreAuthenticate = true;

HttpResponseMessage respone = httpClient.Get(uri);
HttpContent content = respone.Content;

In a web service in another application that is (Info.svc), I have the following code in the service constructor.

var validator = new UserNamePasswordValidator();
var cred = System.Net.CredentialCache.DefaultCredentials; //this one is empty, maybe a solution?
validator.Validate("Username", "Password");

if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
//This throws a 401 unauthorize, which is shown as a 500 error in the central application
throw new WebProtocolException(HttpStatusCode.Unauthorized, "You must be authorized to perform this action.", null);
}
else
{
_userIsAbleToUseService = true;
}

Instead of the username and password in the verification function, I want to use network credentials transferred from another web service, can this be achieved? And How? Any other suggestions are welcome! I can specify the password now in the verification function, but this is not what I want.

- UPDATE-- This is the configuration in web.config for the central application

<authorization>
            <allow roles="administrators"/>
            <deny roles="datareaders"/>
            <deny users="?"/>
        </authorization>

<authentication mode="Forms">
            <forms loginUrl="~/Logon/Logon" timeout="2880"/>
        </authentication>
        <membership>
            <providers>
                <clear/>
                <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="CentralApplication"/>
            </providers>
        </membership>

                                                                         

This part is for web.config in the second web application.

<authentication mode="Forms">
      <forms name="AllPages" loginUrl="~/Logon/" timeout="360" enableCrossAppRedirects="false" />
    </authentication>
    <authorization>
      <!-- NOTE: See Web.config under Private folder for specifics on secure pages. -->
      <deny users="?" />
    </authorization>

<membership defaultProvider="NHMembershipProvider">
      <providers>
        <clear />
        <add name="NHMembershipProvider" applicationName="Website" type="Website.Security.Authentication.Membership.CmsMembershipProvider" description="Stores and retrieves membership data from SQL server using Nhibernate" connectionStringName="NHibernate" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
      </providers>
    </membership>
    <roleManager enabled="true" defaultProvider="NHRoleProvider">
      <providers>
        <clear />
        <add name="NHRoleProvider" applicationName="Website" type="Website.Security.Authentication.Membership.CmsRoleProvider" />
      </providers>
    </roleManager>

. - , ( ). , , URL- - . - - ( -), .

+3
1

2 , , . WcfRestContrib. , webconfig . , .

web.config;

<system.serviceModel>
    <extensions>
      <behaviorExtensions>
        <add name="webAuthentication" type="WcfRestContrib.ServiceModel.Configuration.WebAuthentication.ConfigurationBehaviorElement, WcfRestContrib, Version=1.0.6.107, Culture=neutral, PublicKeyToken=89183999a8dc93b5"/>
        <add name="errorHandler" type="WcfRestContrib.ServiceModel.Configuration.ErrorHandler.BehaviorElement, WcfRestContrib, Version=1.0.6.107, Culture=neutral, PublicKeyToken=89183999a8dc93b5"/>
        <add name="webErrorHandler" type="WcfRestContrib.ServiceModel.Configuration.WebErrorHandler.ConfigurationBehaviorElement, WcfRestContrib, Version=1.0.6.107, Culture=neutral, PublicKeyToken=89183999a8dc93b5"/>
      </behaviorExtensions>
    </extensions>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Rest">
          <webAuthentication requireSecureTransport="false" authenticationHandlerType="WcfRestContrib.ServiceModel.Dispatcher.WebBasicAuthenticationHandler, WcfRestContrib" usernamePasswordValidatorType="CMS.Backend.Services.SecurityValidator, CMS.Backend" source="CMS.Backend"/>
          <!--<webAuthentication requireSecureTransport="false" authenticationHandlerType="CMS.Backend.Services.WebBasicAuthenticationHandler, CMS.Backend" usernamePasswordValidatorType="CMS.Backend.Services.SecurityValidator, Website.Backend" source="CMS.Backend"/>-->
          <errorHandler errorHandlerType="WcfRestContrib.ServiceModel.Web.WebErrorHandler, WcfRestContrib"/>
          <webErrorHandler returnRawException="true" logHandlerType="Website.Backend.Services.LogHandler, Website.Backend" unhandledErrorMessage="An error has occured processing your request. Please contact technical support for further assistance."/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
  </system.serviceModel>

, :

[ServiceContract]
public interface ICmsInfo
{
    [OperationContract]
    [OperationAuthentication]
    [WebInvoke(UriTemplate = "account", Method = "GET")]
    AccountDTO GetAccountInfo();

, , 2 attritubes ;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceConfiguration("Rest", true)]
public class Cmsinfo : ICmsInfo
{
//foo
}

WcfRestContrib , , . , .

- -, . .

0

Source: https://habr.com/ru/post/1766953/


All Articles