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

时间:2019-01-30 13:16:17

标签: c# asp.net-web-api asp.net-apicontroller

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



    }

5 个答案:

答案 0 :(得分:1)

您可以从@Configuration @ConditionalOnClass(name = Constants.DB2_PRESENCE_TOKEN_CLASS) @AutoConfigureAfter(value = { DataSourceAutoConfiguration.class}) @Slf4j public class Db2CustomPropertiesAutoConfiguration implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { log.debug("bean {}", bean); if (bean instanceof DataSourceProxy && ((DataSource) bean).getDriverClassName().equals("com.ibm.db2.jcc.DB2Driver")) { ((DataSource) bean).getDbProperties().put("clientDebugInfo", "XXX") } return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { return bean; } } 获取Api Controller中的当前登录用户,而无需像这样引用任何名称空间,

IPrincipal

您还可以从... var user = User; //<= "User" comes from System.Security.Principal.IPrincipal ... 获得其他属性,例如

  • AuthenticationType
  • 已通过身份验证
  • 名称

根据此类用户的身份,

IPrincipal

编辑:

您可以使用var authType = User.Identity.AuthenticationType; var isAuthenticated = User.Identity.IsAuthenticated; var name = User.Identity.Name; 之类的方法将自定义字段添加为对您的身份的声明,

GrantResourceOwnerCredentials

然后在Api控制器操作方法中,您可以获得类似的UserId,

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

编辑1:

在这里,我从声明中获得了var userId = ((ClaimsIdentity)User.Identity).FindFirst("UserId"); var userName = ((ClaimsIdentity)User.Identity).FindFirst("UserName"); UserId

enter image description here

并且通过angular js HTTP,您可以发送auth承载令牌,例如

UserName

通过在斜角使用上述代码,您的请求将通过Http为每个请求添加身份验证令牌

详细了解$http

编辑2:

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'; }); 中将您希望随身携带的这些数据添加到工作单元存储库中,例如,

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

答案 1 :(得分: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;

//代替此..您可以将其保存在本地存储中,并在注销或超时//计时器后将其删除

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


    }

答案 2 :(得分:0)

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

这种方式很好用,但是我不得不在标题中发送令牌

答案 3 :(得分:0)

在 MVC 控制器中:

var user = await _userManager.GetUserAsync(User);

在 API 控制器中,使用这个:

var user = await _userManager.FindByNameAsync(User.Identity.Name);

确保用户在控制器和页面开头使用 authorize 属性经过身份验证

[Authorize]

答案 4 :(得分:-2)

您无法在api调用中使用会话,每次您需要对用户进行身份验证时,都必须发送该用户的令牌

您可以阅读有关JWT进行身份验证的信息

相关问题