Exemplo n.º 1
0
        public async Task <IActionResult> RegisterExternal([FromBody] RegisterExternalBindingModel model)
        {
            EnsureDatabaseCreated(_applicationDbContext);
            if (ModelState.IsValid)
            {
                var isValid = await _externalAuthManager.VerifyExternalAccessToken(model.AccessToken, model.Provider);

                if (!isValid)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "Invalid access_token, this usually happens when it is expired"
                    }));
                }

                var profile = await _externalAuthManager.GetProfile(model.AccessToken, model.Provider);

                var user = new ApplicationUser {
                    UserName  = profile.email,
                    Email     = profile.email,
                    FirstName = profile.first_name,
                    LastName  = profile.last_name
                };
                var externalAccount = new ExternalAccount()
                {
                    Id             = Guid.NewGuid().ToString(),
                    AddedAt        = DateTimeOffset.Now,
                    Provider       = model.Provider,
                    ProviderUserId = profile.id
                };
                user.ExternalAccounts.Add(externalAccount);

                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    return(Ok());
                }
                AddErrors(result);
            }

            // If we got this far, something failed.
            return(BadRequest(ModelState));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Exchange(OpenIdConnectRequest request)
        {
            if (request.IsPasswordGrantType())
            {
                var user = await _userManager.FindByNameAsync(request.Username);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Ensure the user is allowed to sign in.
                if (!await _signInManager.CanSignInAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    }));
                }

                // Reject the token request if two-factor authentication has been enabled by the user.
                if (_userManager.SupportsUserTwoFactor && await _userManager.GetTwoFactorEnabledAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The specified user is not allowed to sign in."
                    }));
                }

                // Ensure the user is not already locked out.
                if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                // Ensure the password is valid.
                if (!await _userManager.CheckPasswordAsync(user, request.Password))
                {
                    if (_userManager.SupportsUserLockout)
                    {
                        await _userManager.AccessFailedAsync(user);
                    }

                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The username/password couple is invalid."
                    }));
                }

                if (_userManager.SupportsUserLockout)
                {
                    await _userManager.ResetAccessFailedCountAsync(user);
                }

                // Create a new authentication ticket.
                var ticket = await CreateTicketAsync(request, user);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }

            else if (request.GrantType == "urn:ietf:params:oauth:grant-type:external_identity_token")
            {
                //Assertion should be the access_token
                // Reject the request if the "assertion" parameter is missing.
                if (string.IsNullOrEmpty(request.Assertion))
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "The mandatory 'assertion' parameter was missing."
                    }));
                }
                ;

                ExternalAuthProviders provider;

                var providerExists = Enum.TryParse(request["provider"].ToString(), out provider);

                if (!providerExists)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "The mandatory 'provider' parameter was missing."
                    }));
                }
                ;

                var isValid = await _externalAuthManager.VerifyExternalAccessToken(request.Assertion, provider);

                if (!isValid)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidRequest,
                        ErrorDescription = "Invalid access_token, this usually happens when it is expired"
                    }));
                }

                var profile = await _externalAuthManager.GetProfile(request.Assertion, provider);

                var user = await _userManager.FindByEmailAsync(profile.email);

                if (user == null)
                {
                    return(BadRequest(new OpenIdConnectResponse
                    {
                        Error = OpenIdConnectConstants.Errors.InvalidGrant,
                        ErrorDescription = "The user does not exist"
                    }));
                }

                var ticket = await CreateTicketAsync(request, user);

                // Create a new ClaimsIdentity containing the claims that
                // will be used to create an id_token and/or an access token.
                //var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

                // Manually validate the identity token issued by Google,
                // including the issuer, the signature and the audience.
                // Then, copy the claims you need to the "identity" instance.

                // Create a new authentication ticket holding the user identity.
                //var ticket = new AuthenticationTicket(
                //    new ClaimsPrincipal(identity),
                //    new AuthenticationProperties(),
                //    OpenIdConnectServerDefaults.AuthenticationScheme);

                //ticket.SetScopes(
                //    OpenIdConnectConstants.Scopes.OpenId,
                //    OpenIdConnectConstants.Scopes.OfflineAccess);

                return(SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme));
            }


            return(BadRequest(new OpenIdConnectResponse
            {
                Error = OpenIdConnectConstants.Errors.UnsupportedGrantType,
                ErrorDescription = "The specified grant type is not supported."
            }));
        }