有没有办法让Api Controller中的当前用户 - c#

有没有办法让Api Controller中的当前用户 - c#我正在使用asp.net授权在客户端使用Angular 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获取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控制器操作方法中,您可以获取以下UserId,

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

编辑1:

在这里,我从声明中得到了UserIdUserName

有没有办法让Api Controller中的当前用户 - c#

从angular js HTTP您可以发送auth承载令牌,例如

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传递工作单元存储库。

单击选项卡链接时,请专注于每个引导选项卡中的First asp:textbox - javascript

我是开发的新手,并开始开发简单的asp.net应用程序。我正在使用每个都有一些asp标签和文本框的bootstrap选项卡。单击该选项卡时,我要重点关注选项卡内容中的第一个文本框。我搜索了各种答案,但都是针对输入字段的(exp:输入type =“ text”)。找不到适用于ASP文本框的任何内容。任何帮助将不胜感激。谢谢 javascript参考方案 ASP…

当回复有时是一个对象有时是一个数组时,如何在使用改造时解析JSON回复? - java

我正在使用Retrofit来获取JSON答复。这是我实施的一部分-@GET("/api/report/list") Observable<Bills> listBill(@Query("employee_id") String employeeID); 而条例草案类是-public static class…

在IE8中可以单击带有警报的“禁用”按钮(Asp.net网站中的浏览器兼容性问题) - c#

我已禁用链接按钮和图像按钮(位于链接按钮内部,以便我可以显示警报),并且在Chrome中可以正常工作,但是当我在IE8中打开该图像时,该图像被禁用,但是当我单击它时,它会显示popup('确定要删除此用户吗?')。为什么在IE8和IE7中出现此错误,我该如何解决。 <asp:LinkButton ID="lnk_DeleteUser"…

更改DropDownList项目取决于另一个DropDownList(OnChange事件)ASP.NET网页中的值 - c#

对不起,我曾经用过MVC,但我从来没有做过类似的事情。好了,可以这么说,我正在实施一个票务系统,用户可以在特定时间和时间预订票务。在“预订”页面中,我有2个DropDownLists,其中一个用于旅行时间,另一个用于该旅行的座位位置。我想要它,所以当用户从第一个DropDownList中选择时间时,Seat Position DropDownList会自动更…

Mongo汇总 - javascript

我的收藏中有以下文件{ "_id": ObjectId("54490b8104f7142f22ecc97f"), "title": "Sample1", "slug": "samplenews", "cat": …