gpt4 book ai didi

c# - 有没有办法在 Api Controller 中获取当前用户

转载 作者:行者123 更新时间:2023-12-02 02:57:25 25 4
gpt4 key购买 nike

this what i got in Claims shown in the picture我正在使用 asp.net 授权通过 Angular js 进行客户端登录,我需要让当前用户登录

我需要让当前用户在我的记录器表中保存任何操作,并且 httpcontext.session.current 为 null ,是否有另一种方法可以在 session 中保存登录的用户或其他东西以便随时获取它

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 获取 Api Controller 中的当前登录用户,并且无需为其引用任何命名空间,

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

然后在 Api Controller 操作方法中,您可以获得这个 UserId,例如,

var userId = ((ClaimsIdentity)User.Identity).FindFirst("UserId");
var userName = ((ClaimsIdentity)User.Identity).FindFirst("UserName");

编辑1:

在这里,我从声明中获取了 UserIdUserName

enter image description here

从 Angular js HTTP 中,您可以发送您的身份验证承载 token ,例如

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 为每个请求添加身份验证 token

了解更多关于$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));

然后在 Controller 方法中读取这些数据,例如

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 来传入您的工作单元存储库。

关于c# - 有没有办法在 Api Controller 中获取当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54441511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com