我有一个使用Identity的MVC项目。这使用户可以注册该站点并创建配置文件。
我有一个单独的WebAPI类,允许嵌入式GSM设备与服务器通信。用户可以在他们的个人资料中注册并添加许多GSM设备。我不得不为嵌入式GSM设备使用基本身份验证过滤器,因为它们无法缓存令牌/ cookie。
我的问题是,如何在webAPI控制器中查找请求的用户名?我已经尝试按照建议使用RequestContext.Principal访问用户,但它返回null。
控制器:
[BasicAuthentication]
public void Post([FromBody]string value)
{
// Get username from request for database lookup?
}
过滤器:
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedAuthenticationToken = Encoding.UTF8.GetString(Convert.FromBase64String(authenticationToken));
string[] usernamePasswordArray = decodedAuthenticationToken.Split(':');
string username = usernamePasswordArray[0];
string password = usernamePasswordArray[1];
if (GSMSecurity.Login(username, password))
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
编辑:
我找到了用户名:
System.Threading.Thread.CurrentPrincipal;
答案 0 :(得分:1)
如果您的控制器继承自System.Web.Http.ApiController
,您可以访问User
属性:
[BasicAuthentication]
public void Post([FromBody]string value)
{
var name = User.Identity.Name;
}
在BasicAuthentication
中,请不要忘记在登录时正确设置主要属性:
if (GSMSecurity.Login(username, password))
{
var currentPrincipal = new GenericPrincipal(new GenericIdentity(username), null);
actionContext.RequestContext.Principal = currentPrincipal;
Thread.CurrentPrincipal = currentPrincipal;
HttpContext.Current.User = currentPrincipal;
}
答案 1 :(得分:0)
您可以在RequestContext.Principal
答案 2 :(得分:0)
您还应该考虑在HttpContext上设置主体
if (GSMSecurity.Login(username, password)) {
var principal = new GenericPrincipal(new GenericIdentity(username), null);
System.Threading.Thread.CurrentPrincipal = principal;
if (System.Web.HttpContext.Current != null) {
System.Web.HttpContext.Current.User = principal;
}
}
然后通过User
ApiController
媒体资源访问它
[BasicAuthentication]
public void Post([FromBody]string value) {
// Get username from request for database lookup?
var username = User.Identity.Name;
//...
}
框架将从上下文中提取用户信息并将其与请求上下文相关联。