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数据库连接,只是为了检索一些数据,只是为了举例,谢谢有人能帮助我。