【发布时间】:2017-07-05 22:18:52
【问题描述】:
我已经在 C# 中完成了基于令牌身份验证的 webapi,我的问题是当我需要将用户验证到另一个服务器中的 SQL Server 数据库中时,一切正常,直到我针对连接执行读取器,然后它返回错误浏览器中的 CORS,当我删除阅读器时工作正常并返回令牌,但我需要使用 SQL Server 进行验证,这是我的代码:
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;
}
我做了一个简单的数据库连接,只是为了检索一些数据,仅作为示例,如果有人可以帮助我,谢谢。
【问题讨论】:
标签: c# angularjs cors asp.net-web-api2