I have a web application with roles and membership. It works fine. This is an example of the controller:
[InitializeSimpleMembership]
public class MyController : ApiController, IDisposable
{
...
[Authorize(Roles = "Admin")]
[HttpPost]
public HttpResponseMessage MyAction(MyViewModel vm)
{
//...
}
}
I wanted to create a test to check the authorization of the methods, but I get an authorization error [HTTP Error 401 Unauthorized] - although I login with the correct credentials and this user has the right role.
[TestMethod]
public void MyTest()
{
Login("Admin1", "123546", true); // true/false - remember me
var json = new { Key1 = "Val1", Key2 = Val2 };
string methodURL = "My/MyAction";
string method = "Post";
JavaScriptSerializer jss = new JavaScriptSerializer();
string jsonChanged = jss.Serialize(json);
HttpStatusCode hsc = MyWebRequest(methodURL, method, jsonChanged);
Assert.AreEqual(HttpStatusCode.OK, hsc);
}
private static HttpStatusCode MyWebRequest(string methodURL, string method, string json)
{
string URL = "http://localhost/MySite/Action/" + methodURL;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = method;
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Close();
}
HttpWebResponse httpResponse;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); // This is where I get my error
return httpResponse.StatusCode;
}
catch (System.Net.WebException ex)
{
return HttpStatusCode.Unauthorized;
}
}
private static void Login(string userName, string password, bool remeberMe)
{
const string URL = "http://localhost/MySite";
string Login_URL = "/Account/Login";
var request = (HttpWebRequest)WebRequest.Create(URL + Login_URL);
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Method = "POST";
ASCIIEncoding encoding = new ASCIIEncoding();
string stringData = "UserName=" + userName + "&Password=" + password + "&RememberMe=" + remeberMe;
byte[] data = encoding.GetBytes(stringData);
request.ContentLength = data.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
string res = string.Empty;
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream(),true))
{
res = streamReader.ReadToEnd();
}
}
What's the right way to test authorizations methods in tests?
Aucun commentaire:
Enregistrer un commentaire