i正在使用asp.net授权与客户端角JS登录,我需要获得当前用户登录
我需要获得当前用户保存在我的记录表的任何操作,并httpcontext.session.current为null,则有另一种方式来保存登录的用户在会话或者一些别的东西随时得到它
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
{
private readonly string _publicClientId;
static ERPV02_03Entities db;
public ApplicationOAuthProvider(string publicClientId)
{
if (publicClientId == null)
{
throw new ArgumentNullException("publicClientId");
}
db = SingleTonConText.Instance;
_publicClientId = publicClientId;
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(user.UserName);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
{
context.AdditionalResponseParameters.Add(property.Key, property.Value);
}
var data= Task.FromResult<object>(null);
return data;
}
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resourcee owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
{
if (context.ClientId == _publicClientId)
{
Uri expectedRootUri = new Uri(context.Request.Uri, "/");
if (expectedRootUri.AbsoluteUri == context.RedirectUri)
{
context.Validated();
}
}
return Task.FromResult<object>(null);
}
private static View_Emps GetUserInfo(string username)
{
var user = new View_Emps();
try
{
user = db.View_Emps.FirstOrDefault(p =>
p.Emp_UserName == username);
HttpContext.Current.Session.Add("user", user);
}
catch (Exception e)
{
throw e;
}
return user;
}
public static AuthenticationProperties CreateProperties(string userName)
{
var user = GetUserInfo(userName);
JavaScriptSerializer js = new JavaScriptSerializer();
var res = js.Serialize(user);
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "User", res }
};
return new AuthenticationProperties(data);}}
public void SaveLog( T Obj, string Operation)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST IpAddress
string myIP = Dns.GetHostEntry(hostName).AddressList[0].ToString();
var user = HttpContext.Current.Session["user"] as View_Emps;
MyLogger.Data = new JavaScriptSerializer().Serialize(Obj);
MyLogger.OperationType = Operation;
MyLogger.TableName = typeof(T).Name;
MyLogger.DateTime = DateTime.Now;
MyLogger.User_ID = user.Emp_ID;
MyLogger.IP_Address = myIP;
db.Loggers.Add(MyLogger);
Commit();
}
您可以在阿比控制器从IPrincipal
获取当前登录的用户,你将不需要引用任何命名空间像,
...
var user = User; //<= "User" comes from System.Security.Principal.IPrincipal
...
您也可以从像IPrincipal
得到其他属性
从这些用户的身份一样,
var authType = User.Identity.AuthenticationType;
var isAuthenticated = User.Identity.IsAuthenticated;
var name = User.Identity.Name;
编辑:
您可以在GrantResourceOwnerCredentials
方法要求添加自定义字段,以您的身份一样,
...
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
oAuthIdentity.AddClaim(new Claim("UserId", user.Id)); //<= The UserId add here as claim
oAuthIdentity.AddClaim(new Claim("UserName", user.UserName)); //<= The UserName add here as claim
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
...
然后在阿比控制器的操作方法,你可以得到这个用户ID一样,
var userId = ((ClaimsIdentity)User.Identity).FindFirst("UserId");
var userName = ((ClaimsIdentity)User.Identity).FindFirst("UserName");
编辑1:
在这里,我得到了索赔UserId
和UserName
。
而从角JS HTTP,您可以发送您的身份验证令牌承载像
module.run(function($http) {
$http.defaults.headers.common.Authorization = 'bearer TGAf8ViNUtzb9RP9OCBXHN4Ewm0dQbTMb6x4wJMgi4Wk8pq-QEQLIhp_W1A-9jQa7Rlqa60vsQ2ubbjUL0wGosEwaHFDlbdkQqXbOP_VlBJMxN2KnGQZnmvWZvpLPqMF-jpWzPDvBwtVHnh3AjLviPX0gPQjxZAC1ujIeB0p-QZ8yE1VCnLa8Xql01XDXlLVBCzk1UOqt_er-Gx6pL8SemayY8dqVVUgSZTYhcceLLuWQ-Cy3QATJmoJ41K-7ktAeUTz5H7V3ImlC_b8qnnN8sj7k7WRT51q27pUO4-bzJzkD4LGVvDUqaeAhBEqKyS9TkpMIFbRDMol5ZiJcp2vTunOOYP42Mw7GJv09ctoXegKkWo1LWDsSDxeWP5KQed_VGX193pZvQtvz06g2iyXwuP8Q6NaJcXTF43-M9p2HWgGuXT531YXv59euaWevj1AMJkazlZ61uzYi7KGLHKgCwzAMXLKwzBGK4QP0C4tqonowSdTttH93LBOJHjrDepk';
});
通过使用上述代码在角侧您的要求将增加的身份验证令牌用于通过HTTP每个请求
了解更多关于$http
编辑2:
添加这些数据要被在你的工作仓库的单位进行像GrantResourceOwnerCredentials
的要求,
oAuthIdentity.AddClaim(new Claim("Id", user.Id));
oAuthIdentity.AddClaim(new Claim("UserName", user.UserName));
oAuthIdentity.AddClaim(new Claim("Email", user.Email));
oAuthIdentity.AddClaim(new Claim("PhoneNumber", user.PhoneNumber));
然后阅读在你的控制器方法的数据,如
ClaimsPrincipal principal = Request.GetRequestContext().Principal as ClaimsPrincipal;
var claims = principal.Claims.Select(x => new { type = x.Type, value = x.Value });
var id = claims.Where(x => x.type == "Id").FirstOrDefault().value;
var userName = claims.Where(x => x.type == "UserName").FirstOrDefault().value;
var email = claims.Where(x => x.type == "Email").FirstOrDefault().value;
var phoneNumber = claims.Where(x => x.type == "PhoneNumber").FirstOrDefault().value;
ApplicationUser applicationUser = new ApplicationUser //This model is pre generated by web api project and reside in `Models` folder
{
Id = id,
UserName = userName,
Email = email,
PhoneNumber = phoneNumber
};
现在,您可以自由使用这个对象applicationUser
在你的工作仓库的单位通过。
public void SaveLog( T Obj, string Operation)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST IpAddress
string myIP = Dns.GetHostEntry(hostName).AddressList[0].ToString();
var user = HttpContext.Current.Session["user"] as View_Emps;
//而不是这个.. u能在这个本地存储和删除后注销或超时//计时器
MyLogger.Data = new JavaScriptSerializer().Serialize(Obj);
MyLogger.OperationType = Operation;
MyLogger.TableName = typeof(T).Name;
MyLogger.DateTime = DateTime.Now;
MyLogger.User_ID = user.Emp_ID;
MyLogger.IP_Address = myIP;
db.Loggers.Add(MyLogger);
Commit();
}
var UserName = User.Identity.Name;
var UserId = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault().Value;
它的工作原理以及与方式,但我曾在报头发送令牌虽然
你不能在API调用使用会话,每次需要验证用户必须发送用户的令牌
你可以看到智威汤逊认证