1
我已經在C#中完成了基於令牌認證的webapi,我的問題是當我需要驗證用戶到另一臺服務器中的SQL Server數據庫時,一切正常,直到我執行讀者對該連接,然後返回CORS的錯誤在瀏覽器中,當我刪除讀者工作正常,返回的道理,但我需要與SQL Server進行驗證,這裏是我的代碼:C#WebApi 2 CORS不工作當ExecuteReader
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
string nombre = "";
string cadenaConexion = "Data Source=ipSQLServer;Initial Catalog=EDELIVERY;Persist Security Info=True;User ID=userDataBase;Password=PasswdUserDataBase";
SqlConnection conn = new SqlConnection(cadenaConexion);
conn.Open();
string sql = "select * from Usuario a inner join TipoUsuario b on a.CodTipoUsuario = b.Codigo where a.Usuario = '" + context.UserName + "' and a.Clave = '" + context.Password + "');";
SqlCommand cmd = new SqlCommand(sql);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
nombre = reader.GetString(0).ToString().Trim();
}
}
reader.Close();
conn.Close();
if (context.UserName == "admin" && context.Password == "admin")
{
identity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
identity.AddClaim(new Claim("username", "admin"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Nombre Admin"));
context.Validated(identity);
}
else if (context.UserName == "user" && context.Password == "user")
{
identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
identity.AddClaim(new Claim("username", "user"));
identity.AddClaim(new Claim(ClaimTypes.Name, "Nombre Usuario"));
context.Validated(identity);
}
else {
context.SetError("error_grant", "Provided username and password is incorrect");
return;
}
}
下面是代碼的客戶端是在angularjs:
loginApi: function (infoLogin) {
var deferred = $q.defer();
var url = "http://localhost:51372/token";
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: 'username='+infoLogin.usuario+'&password='+infoLogin.passwd+'&grant_type=password'
}).then(function (resp, status, headers, config) {
deferred.resolve(resp);
},
function (err, status, headers, config) {
deferred.reject(err);
});
return deferred.promise;
}
我做了一個SIM卡ple數據庫連接,只是爲了檢索一些數據,只是爲了舉例,謝謝有人能幫助我。