URL 上的 MVC 凭据

MVC Credential on URL

使用 MVC,在控制器中,我将如何传递凭据的值?不将凭据作为查询参数

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

谢谢

使用 POST 请求,以便可以通过请求 headers

发送凭据

发出 Post 请求,并在 ajax 请求的 headers 中提及您的参数,也可以 encode/encrypt。

greater than jQuery 1.5, you can $.ajaxsetup to set headers globally.

 $.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);  
}  });  

然后在控制器中放入授权过滤器来解密和分离凭据。

如果您想通过控制器操作访问它,您可以这样做。

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); } }

通过这种方式,您可以在不传递数据或 url 字符串的情况下授权和验证凭据。