Exemplo n.º 1
0
        public async Task <IHttpActionResult> RegisterWithExternalToken(LoginWithExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // validate token
            ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken);

            if (externalLogin == null)
            {
                return(BadRequest("External login could not be found"));
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                return(BadRequest("Login provider does not match"));
            }

            var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

            // if we reached this point then token is valid, so query the user
            var user = await UserManager.FindAsync(passedLoginInfo);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                // the user has not been registered into the database yet
                // first we need to retrieve info for the user and register him/her

                user = await RetrieveUserDetailsWithProvider(model.Provider, model.ExternalToken);

                var result = await UserManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    var userLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

                    result = await UserManager.AddLoginAsync(user.Id, userLoginInfo);

                    if (result.Succeeded)
                    {
                        // TODO: gseng - add this user to the "asp_net_user_roles" table

                        AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                        Authentication.SignIn(properties);
                    }
                }
            }
            else
            {
                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties);
            }

            return(Ok());
        }
Exemplo n.º 2
0
        public async Task <IHttpActionResult> LoginWithExternalToken(LoginWithExternalTokenBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // validate token
            ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken);

            if (externalLogin == null)
            {
                return(BadRequest("External login could not be found"));
            }

            if (externalLogin.LoginProvider != model.Provider)
            {
                Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);

                return(BadRequest("Login provider does not match"));
            }

            var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey);

            // if we reached this point then token is valid, so query the user
            var user = await UserManager.FindAsync(passedLoginInfo);

            bool hasRegistered = user != null;

            if (!hasRegistered)
            {
                return(BadRequest("User has not been registered yet, must be a business error."));
            }
            else
            {
                ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                    OAuthDefaults.AuthenticationType);

                ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
                                                                                     CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
                Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);

                oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
                oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

                AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());

                DateTime currentUtc = DateTime.UtcNow;
                ticket.Properties.IssuedUtc  = currentUtc;
                ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365));

                string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket);
                Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);

                int expiryInDays = int.Parse(ConfigurationManager.AppSettings["TokenExpiryInDays"]);

                // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint
                JObject token = new JObject(
                    new JProperty("userName", user.UserName),
                    new JProperty("access_token", accessToken),
                    new JProperty("token_type", "bearer"),
                    new JProperty("expires_in", TimeSpan.FromDays(expiryInDays).TotalSeconds.ToString()),
                    new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", CultureInfo.InvariantCulture)),
                    new JProperty("expires", currentUtc.Add(TimeSpan.FromDays(expiryInDays)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture))
                    );

                return(Ok(token));
            }
        }