简体   繁体   English

URL上的MVC凭证

[英]MVC Credential on URL

Using the MVC, In controller, how will I pass the values of credentials? 使用MVC,在控制器中,我将如何传递凭据的值? Without placing the credentials as Query Parameters 不将凭据作为查询参数

// http://user1:pass1@localhost:80/GetData?Branch=1
public ActionResult GetPDF(int Branch) {
    // how will i get user1 as username, and pass1 as password?
}

Thanks 谢谢

Make a Post request with mention your parameters in to the headers of ajax request, one can encode/encrypt as well. 发出一个Post请求,并在ajax请求的标头中提及您的参数,一个也可以编码/加密。

greater than jQuery 1.5, you can $.ajaxsetup to set headers globally. 大于jQuery 1.5,您可以$ .ajaxsetup全局设置标头。

 $.ajax({  
url: 'url',  
type: "POST",  
contentType: "application/json",  
data: JSON.stringify(Data),  
dataType: "json",  
headers: { 'Authorization' :'Basic ' + Encode(username + ':' + password) },  
success: function (result) {  

},  
error: function (err) {  
    alert(err.statusText);  
}  });  

then into the controller put the authorization filter to decrypt and separate the credentials. 然后将授权过滤器放入控制器,以解密和分离凭据。

In case you want to access it through your controller action you can do something like this. 如果您想通过控制器操作来访问它,可以执行以下操作。

var re = Request;
var headers = re.Headers;

if (headers.Contains("Username"))
{
    string token = headers.GetValues("Username").First();
}

public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
// Gets header parameters
string authenticationString = actionContext.Request.Headers.Authorization.Parameter;

string originalString = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationString)); // Gets username and password string usrename = originalString.Split(':')[0]; string password = originalString.Split(':')[1]; // Validate username and password if (!ApiSecurity.VaidateUser(usrename, password)) { // returns unauthorized error actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized); } } base.OnAuthorization(actionContext); } }

this way you can authorize and authenticate the credentials without passing to data or url string. 这样,您可以授权和认证凭据,而无需传递给数据或url字符串。

使用POST请求,以便可以通过请求标头发送凭据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM