开发者

HttpContext.User.Idenity is empty

开发者 https://www.devze.com 2022-12-19 06:56 出处:网络
I\'m using asp.net and trying to assign roles for a user with forms authentication like this: public ActionResult AdminLogin(string password, string username)

I'm using asp.net and trying to assign roles for a user with forms authentication like this:

    public ActionResult AdminLogin(string password, string username)
    {
        User _user = _us.GetUsers(username, password).FirstOrDefault();

        if (_user != null)
        {
            string _username = _user.Username;

            FormsAuthentication.SetAuthCookie(_username, false);

            string[] _roles = _us.GetUserRoles(_username);


            HttpContext.User = new GenericPrincipal(HttpContext.User.Identity, _roles);


            return RedirectToAction("Index", "Admin");

When I debug HttpContext.User.Identity always is null, but _username and _roles contains the proper 开发者_运维知识库data. Howto fix this?

/M


Your action is setting the User IPrincipal for the current context. As soon as you redirect to your other action (and all subsequent requests) a new HttpContext is created with a null User IPrincipal.

What you could do is persist the information in the authentication cookie and then extract that data in the Application_AuthenticateRequest method in your Global.asax file and set the User property of the HttpContext there.

This answer contains more details and example code


I believe the issue is that you are just setting the user as authenticated, and therefore, the HttpContext is not updated yet since the auth cookie has not yet been set on the users side of the request.


I was struggling too.

I was trying to carryout my authentication and authorization inside a WCF service using standard ASP.Net Membership and Role providers.

I wanted to pass in credentials and a 'requested app' to determine if the user 'authenticated' for that app. (not the ASP.Net APP, but an app in my own database).

To do this, I wanted access to the roles, but didn't want to 'redirect' or have a second call to my WCF service.

Here is some code that works for me:

First I determine if the user is valid as follows:

if (Membership.ValidateUser(CompanyCn, CompanyPwd))
{
    sbLogText.AppendFormat("\r\n\r\n\tValid User UID/PWD: '{0}'/'{1}'", CompanyCn, CompanyPwd);
    FormsAuthentication.SetAuthCookie(CompanyCn, false);
}

Then the following code workes nicely for getting the list of roles:

List<string> roleList = new List<string>(Roles.GetRolesForUser(CompanyCn));
sbLogText.AppendFormat("\r\n\r\n\tUser ('{0}'): Roles ({1}):", CompanyCn, roleList.Count);
foreach (string s in roleList)
    sbLogText.AppendFormat("\r\n\t\tRole: {0}", s);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号