开发者

I implemented custom authentication but how to get UserID through application

开发者 https://www.devze.com 2023-03-31 12:16 出处:网络
I implemented custom authentication/authorization based on this tutorial http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MV

I implemented custom authentication/authorization based on this tutorial http://www.mattwrock.com/post/2009/10/14/Implementing-custom-Membership-Provider-and-Role-Provider-for-Authinticating-ASPNET-MVC-Applications.aspx It works fine. I implemented it because I don't want to have stored procedures in my database and possibility to use 开发者_如何学Cdifferent RDBMS. But I have one issue here. I authenticate user but I don't know how to store UserId somewhere so when I need to get something from database based on UserID to get it. Something like:

List<Product> products = productsRepository.GetProductsByUserId(User.UserID);

How to make this?

BTW Is there any better way to make custom authentication/authorization than this from this tutorial?

Thanks


If you've actually implemented all the methods, and you're populating the built-in MembershipUser, then simply Membership.GetUser().ProviderUserKey will return ther UserId.


in my solution I use

 Docent docent = DocentRepo.GetByID(User.Identity.Name);

maybe this can be of use to you


If you're using FormsAuthentification you can encode some custom user data in your cookie / ticket besides UserName. But you have to manually create a FormsAuthenticationTicket and set UserData property to the user's id during login. This way you can have both UserName & UserId.

        // during login
        var authCookie = FormsAuthentication.GetAuthCookie(userName, createPersistentCookie);
        var ticket = FormsAuthentication.Decrypt(authCookie.Value);
        // preserve data in your configuration
        var ticketWithId = new FormsAuthenticationTicket(
                                version: ticket.Version,
                                name: ticket.Name,
                                issueDate: ticket.IssueDate,
                                expiration: ticket.Expiration,
                                isPersistent: ticket.IsPersistent,
                                userData: userId);

        authCookie.Value = FormsAuthentication.Encrypt(ticketWithId);
        _context.Response.Cookies.Add(authCookie);

Then you can have an extension method for Controller or HttpContext classes:

    public int? GetUserId(this Controller controller) {
        var identity = (FormsIdentity)controller.User.Identity;
        int id;
        if (int.TryParse(identity.Ticket.UserData, out id))
            return id;
        return null;
    }

But if you don't need both UserId & UserName data for your user, than HttpContext.User.Identity.Name or Controller.User.Identity.Name will have the username for your current user

0

精彩评论

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