Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have Asp.net web Application project with WebApi and individuals user Account.
I implemented Registration and login, and I used angularjs in front end.

Now, I need to store cookies in browser.

I'm confuse if authentication based on cookies store cookies in browser?

In my project I authenticate users based on token.

I do research but it confuse me and I did't find a clear guide to store cookies using Asp.Net Identity webApi.

What I have tried:

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;
        }
       /* 
   I tried the following but I get an error that Request doesn't exist

 var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, context.UserName));
        var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignIn(id);


                 */



        ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
        ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager);

        AuthenticationProperties properties = CreateProperties(user.UserName);
        AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
        context.Validated(ticket);
        context.Request.Context.Authentication.SignIn(cookiesIdentity);
}


Please don't provide me with link to asp.Net Identity MVC, I want WebApi.
Posted
Updated 15-Apr-19 7:23am
v3

1 solution

For Web API, you should reference the following namespace:

C#
Microsoft.Owin.Host.SystemWeb


and then reference the OWIN Context like this:

C#
HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
 
Share this answer
 
Comments
Member 12919448 16-Apr-19 3:23am    
One question, do I have to store cookies in front end? in ngCookies for example ?
In cookies now I just see .AspNet.ApplicationCookie
Vincent Maverick Durano 16-Apr-19 10:45am    
That's all up to you. ngCookies is an angular service which is meant to be used for angular based applications.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900