Ejemplo n.º 1
0
        // Called when a request to the Token endpoint arrives with a "grant_type" of "password".
        // This occurs when the user has provided name and password credentials directly
        // into the client application's user interface, and the client application is using
        // those to acquire an "access_token" and optional "refresh_token".
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var userManager = context.OwinContext.GetUserManager <GbmonoUserManager>();

            // lookup user by user name and password
            GbmonoUser user = await userManager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            // create user identity for Bearer token
            ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, OAuthDefaults.AuthenticationType);

            // create user identity for cookie
            ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager, CookieAuthenticationDefaults.AuthenticationType);

            // create properties, user name or other extra information
            AuthenticationProperties properties = CreateProperties(user);

            // initialize a new instance of the Microsoft.Owin.Security.AuthenticationTicket
            AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);

            // call the context.Validated(ticket) to tell the OAuth server to protect the ticket as an access token and send it out in JSON payload.
            // to issue an access token the context.Validated must be called with a new ticket containing the claims about the resource owner
            // which should be associated with the access token.
            context.Validated(ticket);

            // Signs the cookie identity so it can send the authentication cookie.
            context.Request.Context.Authentication.SignIn(cookiesIdentity);
        }