有没有一种方式来获得当前用户在阿比控制器

问题描述 投票:2回答:4

this what i got in Claims shown in the picturei正在使用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();



    }
c# asp.net-web-api asp.net-apicontroller
4个回答
2
投票

您可以在阿比控制器从IPrincipal获取当前登录的用户,你将不需要引用任何命名空间像,

...
var user = User;   //<= "User" comes from System.Security.Principal.IPrincipal
...

您也可以从像IPrincipal得到其他属性

  • AuthenticationType
  • IsAuthenticated
  • name

从这些用户的身份一样,

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:

在这里,我得到了索赔UserIdUserName

enter image description here

而从角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在你的工作仓库的单位通过。


0
投票

审查该问题Is it possible to set localStorage or Session variable in asp.net page and read it in javascript on the other page?

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


    }

0
投票
var UserName = User.Identity.Name;
var UserId = ((ClaimsIdentity)User.Identity).Claims.FirstOrDefault().Value;

它的工作原理以及与方式,但我曾在报头发送令牌虽然


-2
投票

你不能在API调用使用会话,每次需要验证用户必须发送用户的令牌

你可以看到智威汤逊认证

© www.soinside.com 2019 - 2024. All rights reserved.