WCF: REST + Basic authentification + IIS, authentification
In a recent project, Restful WCF is used to provide services, but the verification mechanism is required. It is too complicated to search for services on the Internet. FQ found a good article to share.
Original link: http://vgolovchenko.wordpress.com/2012/05/20/wcf-soaprest-ssl-basic-authentification-iis/
How to Implement REST + Basic auth?
1. Create a WCF lib host to iis
Reference: http://www.cnblogs.com/yongqiangyue/p/4050258.html
Reference: http://www.cnblogs.com/wlflovenet/archive/2011/10/28/WCFREST.html
2. Use BasicAuthenticationManager to parse and verify the http-header of BasicAuth.
The Code is as follows:
public class BasicAuthenticationManager : ServiceAuthorizationManager { protected override bool CheckAccessCore(OperationContext operationContext) { try { var msg = operationContext.RequestContext.RequestMessage; // If user requests standart help-page then ignore authentication check. if (msg.Properties.ContainsKey("HttpOperationName") && msg.Properties["HttpOperationName"].ToString() == "HelpPageInvoke") { return base.CheckAccessCore(operationContext); } var httpRequestHeaders = ((HttpRequestMessageProperty) msg.Properties[HttpRequestMessageProperty.Name]).Headers; // Is Authorization-header contained in http-headers? if (!httpRequestHeaders.AllKeys.Contains(HttpRequestHeader.Authorization.ToString())) { return false; } // Try to parse standart Basic-auth header. var authenticationHeaderBase64Value = httpRequestHeaders[HttpRequestHeader.Authorization.ToString()]; var basicAuthenticationFormatString = Base64EncodeHelper.DecodeUtf8From64(authenticationHeaderBase64Value).Remove(0, "Basic ".Length); var basicAuthenticationParams = basicAuthenticationFormatString.Split(new[] {':'}, 2); var login = basicAuthenticationParams.FirstOrDefault(); var password = basicAuthenticationParams.LastOrDefault(); // Check credentials.
// Custom authentication method: CAuthorizationAPI is a self-encapsulated method class that verifies the user name and password. if (! CAuthorizationAPI. validate (login, password) {return false ;}} catch (Exception ex) {return false;} return base. checkAccessCore (operationContext) ;}} modify the corresponding configuration file (modification in the behavior-section)
<System. serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled = "true"/> <behaviors> <! -- <EndpointBehaviors> <behavior name = ""> <webHttp helpEnabled = "true" faultExceptionEnabled = "true"/> </behavior> </endpointBehaviors> --> <serviceBehaviors> <behavior> <! -- To avoid metadata leakage, set the following value to false before deployment and delete the above metadata endpoint --> <serviceMetadata httpGetEnabled = "True"/> <! -- To receive fault exception details for debugging, set the following value to true. Set false before deployment to avoid leakage of exception information --> <serviceDebug includeExceptionDetailInFaults = "true"/> <serviceAuthorization serviceAuthorizationManagerType = "DMService. infrastructure. basicAuthenticationManager, DMService "/> </behavior> </serviceBehaviors> </behaviors> </system. serviceModel>
3. Write a test program: Add basic auth http-header
private static void Main(string[] args) { try { var request = WebRequest.Create(string.Format("http://localhost:21568/api/test/yueyq/{0}", Uri.EscapeDataString("rest-client (ssl-basic auth)"))); // ! Remove this string in production code. Emulate working with the trusted certificate. ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; // The straightforward passing of credential parameter for demo. const string login = "user"; const string password = "password"; request.Headers.Add( HttpRequestHeader.Authorization, Base64EncodeHelper.EncodeUtf8To64(string.Format("Basic {0}:{1}", login, password))); using (var reader = new StreamReader(request.GetResponse().GetResponseStream())) { Console.WriteLine(reader.ReadToEnd()); } } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.WriteLine("\n press Enter to exit.."); Console.ReadLine(); }}
4. Implementation of class Base64EncodeHelper
public static class Base64EncodeHelper{ /// <summary> /// The method create a Base64 encoded string from a normal string. /// </summary> /// <param name="toEncode">The String containing the characters to encode.</param> /// <returns>The Base64 encoded string.</returns> public static string EncodeUtf8To64(string toEncode) { var toEncodeAsBytes = Encoding.UTF8.GetBytes(toEncode); var returnValue = Convert.ToBase64String(toEncodeAsBytes); return returnValue; } /// <summary> /// The method to Decode your Base64 strings. /// </summary> /// <param name="encodedData">The String containing the characters to decode.</param> /// <returns>A String containing the results of decoding the specified sequence of bytes.</returns> public static string DecodeUtf8From64(string encodedData) { var encodedDataAsBytes = Convert.FromBase64String(encodedData); var returnValue = Encoding.UTF8.GetString(encodedDataAsBytes); return returnValue; }}
For more information about WCF security, see the following link:
http://wcfsecurityguide.codeplex.com/