Ejemplo n.º 1
0
        public async Task <AuthorisationResult> ExchangeCodeForTokenAsync()
        {
            var apiClient = new AuthenticationApiClient(Config.TenantDomain);

            try
            {
                TokenResponse = await apiClient.GetTokenAsync(new AuthorizationCodeTokenRequest()
                {
                    ClientId     = Config.ClientId,
                    ClientSecret = Config.ClientSecret,
                    Code         = VerificationCode,
                    RedirectUri  = RedirectUrl
                });
            }
            catch (AggregateException ex)
            {
                (new ExceptionLogController()).AddLog(ex);
            }

            return((TokenResponse == null) ? AuthorisationResult.Denied : AuthorisationResult.Authorized);
        }
Ejemplo n.º 2
0
        private static async Task <string> GetAccessTokenAsync(string clientId, string clientSecret, string audience, string domain)
        {
            try
            {
                var authenticationApiClient = new AuthenticationApiClient(domain);

                // Get the access token
                var token = await authenticationApiClient.GetTokenAsync(new ClientCredentialsTokenRequest
                {
                    ClientId     = clientId,
                    ClientSecret = clientSecret,
                    Audience     = audience
                }).ConfigureAwait(false);

                return(token.AccessToken);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Ejemplo n.º 3
0
        public async Task Can_request_token_using_device_code()
        {
            var mockHandler = new Mock <HttpMessageHandler>(MockBehavior.Strict);
            var accessToken = "TEST_ACCESSTOKEN";
            var response    = new AccessTokenResponse {
                AccessToken = accessToken
            };
            var domain         = GetVariable("AUTH0_AUTHENTICATION_API_URL");
            var deviceCode     = "TEST_CODE";
            var expectedParams = new Dictionary <string, string>
            {
                { "grant_type", "urn:ietf:params:oauth:grant-type:device_code" },
                { "device_code", deviceCode },
                { "client_id", GetVariable("AUTH0_CLIENT_ID") }
            };

            mockHandler.Protected()
            .Setup <Task <HttpResponseMessage> >(
                "SendAsync",
                ItExpr.Is <HttpRequestMessage>(req => req.RequestUri.ToString() == $"https://{domain}/oauth/token" && ValidateRequestContent(req, expectedParams)),
                ItExpr.IsAny <CancellationToken>()
                )
            .ReturnsAsync(new HttpResponseMessage()
            {
                StatusCode = HttpStatusCode.OK,
                Content    = new StringContent(JsonConvert.SerializeObject(response), Encoding.UTF8, "application/json"),
            });

            var httpClient = new HttpClient(mockHandler.Object);
            var authenticationApiClient = new AuthenticationApiClient(domain, new HttpClientAuthenticationConnection(httpClient));

            var tokenReponse = await authenticationApiClient.GetTokenAsync(new DeviceCodeTokenRequest
            {
                ClientId   = GetVariable("AUTH0_CLIENT_ID"),
                DeviceCode = deviceCode
            });

            tokenReponse.Should().NotBeNull();
            tokenReponse.AccessToken.Should().Equals(accessToken);
        }
Ejemplo n.º 4
0
        private static async Task Main()
        {
            const string auth0Domain = @"mova-user-id-test.auth0.com";

            var httpClient = new HttpClient();

            var auth = new AuthenticationApiClient(
                domain: auth0Domain,
                connection: new HttpClientAuthenticationConnection(httpClient: httpClient)
                );

            var token = await auth.GetTokenAsync(request : new ClientCredentialsTokenRequest
            {
                ClientId = "Z7gyil733avwkafs5Aeky3XMmLtBURqy",

                // ReSharper disable StringLiteralTypo
                ClientSecret = "wISWqDR-LN-vjAuux10w-lTYayKsUDrMwfee2QtNBLFrEianzertZjZrUaj26P-n",
                // ReSharper restore StringLiteralTypo

                Audience         = "https://mova-user-id-test.auth0.com/api/v2/",
                SigningAlgorithm = JwtSignatureAlgorithm.RS256
            });

            var api = new ManagementApiClient(
                token: token.AccessToken,
                domain: auth0Domain,
                connection: new HttpClientManagementConnection(httpClient: httpClient)
                );

            foreach (
                var u in await api.Users.GetAllAsync(
                    request: new GetUsersRequest(),
                    pagination: new PaginationInfo())
                )
            {
                await api.Users.DeleteAsync(id : u.UserId);
            }


            var users = new[]
        public async Task <IActionResult> Login(LoginViewModel vm, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    AuthenticationApiClient client = new AuthenticationApiClient(new Uri($"https://{_appSettings.Auth0.Domain}/"));

                    var result = await client.GetTokenAsync(new ResourceOwnerTokenRequest {
                        ClientId     = _appSettings.Auth0.ClientId,
                        ClientSecret = _appSettings.Auth0.ClientSecret,
                        Scope        = "openid profile",
                        Realm        = "Username-Password-Authentication", // Specify the correct name of your DB connection
                        Username     = vm.EmailAddress,
                        Password     = vm.Password
                    });

                    // Get user info from token
                    var user = await client.GetUserInfoAsync(result.AccessToken);

                    // Create claims principal
                    var claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.UserId),
                        new Claim(ClaimTypes.Name, user.FullName)
                    }, CookieAuthenticationDefaults.AuthenticationScheme));

                    // Sign user into cookie middleware
                    await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);

                    return(RedirectToLocal(returnUrl));
                }
                catch (Exception e)
                {
                    ModelState.AddModelError("", e.Message);
                }
            }

            return(View(vm));
        }
        public async Task Fails_Token_Validation_With_Incorrect_Audience()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = _connection.Name,
                Scope        = "openid",
                Username     = _user.Email,
                Password     = Password
            });

            var idTokenValidation = new IdTokenRequirements($"https://{GetVariable("AUTH0_AUTHENTICATION_API_URL")}/", "invalid_audience", TimeSpan.FromMinutes(1));

            // Assert
            authenticationResponse.IdToken.Should().NotBeNull();
            await Assert.ThrowsAsync <IdTokenValidationException>(() => idTokenValidation.AssertTokenMeetsRequirements(authenticationResponse.IdToken));
        }
Ejemplo n.º 7
0
        public async Task Can_authenticate_to_default_directory()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Scope        = "openid",
                Username     = _userInDefaultDirectory.Email,
                Password     = Password
            });

            // Assert
            authenticationResponse.Should().NotBeNull();
            authenticationResponse.TokenType.Should().NotBeNull();
            authenticationResponse.AccessToken.Should().NotBeNull();
            authenticationResponse.IdToken.Should().NotBeNull();
            authenticationResponse.RefreshToken.Should().BeNull(); // No refresh token if offline access was not requested
        }
Ejemplo n.º 8
0
        public async Task Can_authenticate_user_with_plus_in_username()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = _connection.Name,
                Scope        = "openid",
                Username     = _plusUser.Email,
                Password     = Password
            });

            // Assert
            authenticationResponse.Should().NotBeNull();
            authenticationResponse.TokenType.Should().NotBeNull();
            authenticationResponse.AccessToken.Should().NotBeNull();
            authenticationResponse.IdToken.Should().NotBeNull();
        }
Ejemplo n.º 9
0
        public async Task Can_authenticate_against_Auth0()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL")));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = connection.Name,
                Scope        = "openid",
                Username     = user.Email,
                Password     = "******"
            });

            // Assert
            authenticationResponse.Should().NotBeNull();
            authenticationResponse.TokenType.Should().NotBeNull();
            authenticationResponse.AccessToken.Should().NotBeNull();
            authenticationResponse.IdToken.Should().NotBeNull();
            authenticationResponse.RefreshToken.Should().BeNull(); // No refresh token if offline access was not requested
        }
Ejemplo n.º 10
0
        private async Task <UserInfo> AuthenticateAuth0Async(LoginRequest loginRequest)
        {
            var teste = $"https://{_configuration.Domain}";

            var client = new AuthenticationApiClient(new Uri(teste));

            var result = await client.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = _configuration.ClientId,
                ClientSecret = _configuration.ClientSecret,
                Scope        = _configuration.Scope,
                Username     = loginRequest?.NickName,
                Realm        = _configuration.Realm,
                Password     = loginRequest?.Password,
                Audience     = _configuration.Audience
            });

            var user = await client.GetUserInfoAsync(result.AccessToken);

            await AddAsyncAuth0(user, loginRequest.Password);

            return(user);
        }
        public async Task <AuthenticationResult> AuthenticateAsync(string userId, string password)
        {
            var result = await _client.GetTokenAsync(new ResourceOwnerTokenRequest {
                Audience     = _audience,
                ClientId     = _clientId,
                ClientSecret = _clientSecret,
                Realm        = _realm,
                Username     = userId,
                Password     = password,
            });

            if (result != null && !string.IsNullOrEmpty(result.AccessToken))
            {
                return(new AuthenticationResult
                {
                    AccessToken = result.AccessToken,
                    ExpiresIn = result.ExpiresIn,
                    TokenType = result.TokenType
                });
            }

            return(null);
        }
Ejemplo n.º 12
0
        public async Task Fails_Token_Validation_With_Incorrect_Domain()
        {
            // Arrange
            using (var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL")))
            {
                // Act
                var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
                {
                    ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                    ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                    Realm        = _connection.Name,
                    Scope        = "openid",
                    Username     = _user.Email,
                    Password     = Password
                });

                var requirements = new IdTokenRequirements(JwtSignatureAlgorithm.RS256, "https://auth0.auth0.com/", GetVariable("AUTH0_CLIENT_ID"), TimeSpan.FromMinutes(1));

                // Assert
                authenticationResponse.IdToken.Should().NotBeNull();
                await Assert.ThrowsAsync <IdTokenValidationKeyMissingException>(() => new IdTokenValidator().Assert(requirements, authenticationResponse.IdToken, GetVariable("AUTH0_CLIENT_SECRET")));
            }
        }
Ejemplo n.º 13
0
        public async Task Can_request_offline_access()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = _connection.Name,
                Scope        = "openid offline_access",
                Username     = _user.Email,
                Password     = Password
            });

            // Assert
            authenticationResponse.Should().NotBeNull();
            authenticationResponse.TokenType.Should().NotBeNull();
            authenticationResponse.AccessToken.Should().NotBeNull();
            authenticationResponse.IdToken.Should().NotBeNull();
            authenticationResponse.RefreshToken.Should().NotBeNull(); // Requested offline access, so we should get a refresh token
        }
        public async Task Passes_Token_Validation_With_CNAME()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("BRUCKE_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("BRUCKE_CLIENT_ID"),
                ClientSecret = GetVariable("BRUCKE_CLIENT_SECRET"),
                Realm        = GetVariable("BRUCKE_CONNECTION_NAME"),
                Scope        = "openid",
                Username     = GetVariable("BRUCKE_USERNAME"),
                Password     = GetVariable("BRUCKE_PASSWORD")
            });

            var         validator      = new IdentityTokenValidator();
            Func <Task> validationFunc = async() =>
                                         await validator.ValidateAsync(authenticationResponse.IdToken, $"https://{GetVariable("BRUCKE_AUTHENTICATION_API_URL")}/", GetVariable("BRUCKE_CLIENT_ID"));

            // Assert
            authenticationResponse.IdToken.Should().NotBeNull();
            validationFunc.Should().NotThrow <IdentityTokenValidationException>();
        }
        public async Task Passes_Token_Validation()
        {
            // Arrange
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // Act
            var authenticationResponse = await authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = _connection.Name,
                Scope        = "openid",
                Username     = _user.Email,
                Password     = Password
            });

            var         validator      = new IdentityTokenValidator();
            Func <Task> validationFunc = async() =>
                                         await validator.ValidateAsync(authenticationResponse.IdToken, $"https://{GetVariable("AUTH0_AUTHENTICATION_API_URL")}/", GetVariable("AUTH0_CLIENT_ID"));

            // Assert
            authenticationResponse.IdToken.Should().NotBeNull();
            validationFunc.Should().NotThrow <IdentityTokenValidationException>();
        }
Ejemplo n.º 16
0
        public async Task GetManagementClientAccessToken(bool regenerate_if_exists = false)
        {
            if (!string.IsNullOrWhiteSpace(_client_access_token) && !regenerate_if_exists)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(_options.TestingClientAccessToken))
            {
                _client_access_token = _options.TestingClientAccessToken;
            }
            else
            {
                var client        = new AuthenticationApiClient(_options.ServerRootUrl);
                var tokenResponse = await client.GetTokenAsync(new ClientCredentialsTokenRequest
                {
                    ClientId     = _options.ClientId,
                    ClientSecret = _options.ClientSecret,
                    Audience     = _options.ApiIdentifier
                });

                _client_access_token = tokenResponse.AccessToken;
            }
        }
Ejemplo n.º 17
0
        public async Task OnGet()
        {
            if (HttpContext.User.IsInRole("Streamer"))
            {
                Redirect(Source ?? "/");
            }

            var client = new AuthenticationApiClient(Configuration["Auth0:Domain"], AuthenticationConnection);

            var token = await client.GetTokenAsync(
                new ClientCredentialsTokenRequest
            {
                Audience     = Configuration["Auth0-Management:Audience"],
                ClientId     = Configuration["Auth0-Management:ClientId"],
                ClientSecret = Configuration["Auth0-Management:ClientSecret"]
            });

            var management = new ManagementApiClient(
                token.AccessToken,
                Configuration["Auth0:Domain"],
                ManagementConnection);

            var claim = HttpContext.User.Claims.Single(c => c.Type == ClaimTypes.NameIdentifier);

            var rolePaged = await management.Roles.GetAllAsync(new GetRolesRequest { NameFilter = "Streamer" });

            await management.Roles.AssignUsersAsync(rolePaged.Single().Id, new AssignUsersRequest
            {
                Users = new[] { claim.Value }
            });

            await HttpContext.ChallengeAsync("Auth0", new AuthenticationProperties
            {
                RedirectUri = Source ?? "/"
            });
        }
        public async Task <IActionResult> Index()
        {
            var authClient = new AuthenticationApiClient(new Uri($"https://{_auth0.Domain}"));
            var token      = await authClient.GetTokenAsync(new ClientCredentialsTokenRequest()
            {
                Audience     = $"https://{_auth0.Domain}/api/v2/",
                ClientId     = _auth0.ClientId,
                ClientSecret = _auth0.ClientSecret
            });

            var mgmtClient = new ManagementApiClient(token.AccessToken, new Uri($"https://{_auth0.Domain}/api/v2"));

            var rules = await mgmtClient.Rules.GetAllAsync(fields : "name,script,order");

            var clients = await mgmtClient.Clients.GetAllAsync(fields : "name,client_id");

            var rulesByClient = clients.Where(c => c.Name != "All Applications").ToDictionary(
                client => client,
                client => new ClientAndMatchedRules()
            {
                Client       = client,
                MatchedRules = new HashSet <Rule>()
            }
                );
            var unmatchedRules = new List <UnmatchedRule>();

            foreach (var rule in rules)
            {
                var applicableClients = _scriptParser.ParseApplicableClients(rule.Script);
                if (applicableClients == null || applicableClients.Count == 0)
                {
                    unmatchedRules.Add(new UnmatchedRule()
                    {
                        RuleName = rule.Name,
                        Reason   = "Couldn't detect clients within script"
                    });
                    continue;
                }
                foreach (var applicable in applicableClients)
                {
                    Client matchingClient;
                    if (!applicable.TryGetMatchingClient(clients, out matchingClient))
                    {
                        unmatchedRules.Add(new UnmatchedRule()
                        {
                            RuleName = rule.Name,
                            Reason   = $"Couldn't find matching client {applicable.GetHumanReadableId()}"
                        });
                        continue;
                    }

                    ClientAndMatchedRules clientAndMatchedRules = rulesByClient[matchingClient];
                    clientAndMatchedRules.MatchedRules.Add(rule);
                }
            }

            return(View(new RulesAndClientMatches()
            {
                ClientAndRules = rulesByClient.Values.ToList(),
                UnmatchedRules = unmatchedRules
            }));
        }
Ejemplo n.º 19
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            AuthenticationApiClient client = new AuthenticationApiClient(
                new Uri(string.Format("https://{0}", ConfigurationManager.AppSettings["auth0:Domain"])));

            var token = await client.GetTokenAsync(new AuthorizationCodeTokenRequest
            {
                ClientId     = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                Code         = context.Request.QueryString["code"],
                RedirectUri  = context.Request.Url.ToString()
            });

            var profile = await client.GetUserInfoAsync(token.AccessToken);

            var user = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("name", profile.FullName ?? profile.PreferredUsername ?? profile.Email),
                new KeyValuePair <string, object>("email", profile.Email),
                new KeyValuePair <string, object>("family_name", profile.LastName),
                new KeyValuePair <string, object>("given_name", profile.FirstName),
                new KeyValuePair <string, object>("nickname", profile.NickName),
                new KeyValuePair <string, object>("picture", profile.Picture),
                new KeyValuePair <string, object>("user_id", profile.UserId),
                new KeyValuePair <string, object>("id_token", token.IdToken),
                new KeyValuePair <string, object>("access_token", token.AccessToken),
                new KeyValuePair <string, object>("refresh_token", token.RefreshToken)
            };

            // NOTE: Uncomment the following code in order to include claims from associated identities
            //profile.Identities.ToList().ForEach(i =>
            //{
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".access_token", i.AccessToken));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".provider", i.Provider));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".user_id", i.UserId));
            //});

            // NOTE: uncomment this if you send roles
            // user.Add(new KeyValuePair<string, object>(ClaimTypes.Role, profile.ExtraProperties["roles"]));

            // NOTE: this will set a cookie with all the user claims that will be converted
            //       to a ClaimsPrincipal for each request using the SessionAuthenticationModule HttpModule.
            //       You can choose your own mechanism to keep the user authenticated (FormsAuthentication, Session, etc.)
            FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(user);

            var state = context.Request.QueryString["state"];

            if (state != null)
            {
                var stateValues = HttpUtility.ParseQueryString(context.Request.QueryString["state"]);
                var redirectUrl = stateValues["ru"];

                // check for open redirection
                if (redirectUrl != null && IsLocalUrl(redirectUrl))
                {
                    context.Response.Redirect(redirectUrl, true);
                }
            }

            context.Response.Redirect("/");
        }
Ejemplo n.º 20
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            AuthenticationApiClient client = new AuthenticationApiClient(
                new Uri(string.Format("https://{0}", ConfigurationManager.AppSettings["auth0:Domain"])));

            string contextCode = context.Request.QueryString["code"];
            var    token       = await client.GetTokenAsync(new AuthorizationCodeTokenRequest
            {
                ClientId     = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                Code         = contextCode,
                RedirectUri  = context.Request.Url.ToString()
            });

            UserInfo profile = await client.GetUserInfoAsync(token.AccessToken);

            //var user = new List<KeyValuePair<string, object>>
            //{
            //    new KeyValuePair<string, object>("name", profile.FullName ?? profile.PreferredUsername ?? profile.Email),
            //    new KeyValuePair<string, object>("email", profile.Email),
            //    new KeyValuePair<string, object>("family_name", profile.LastName),
            //    new KeyValuePair<string, object>("given_name", profile.FirstName),
            //    new KeyValuePair<string, object>("nickname", profile.NickName),
            //    new KeyValuePair<string, object>("picture", profile.Picture),
            //    new KeyValuePair<string, object>("user_id", profile.UserId),
            //    new KeyValuePair<string, object>("id_token", token.IdToken),
            //    new KeyValuePair<string, object>("access_token", token.AccessToken),
            //    new KeyValuePair<string, object>("refresh_token", token.RefreshToken),
            //    new KeyValuePair<string, object>("email_verified", profile.EmailVerified),
            //    new KeyValuePair<string, object>("gender", profile.Gender)
            //};

            // NOTE: Uncomment the following code in order to include claims from associated identities
            //profile.Identities.ToList().ForEach(i =>
            //{
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".access_token", i.AccessToken));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".provider", i.Provider));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".user_id", i.UserId));
            //});

            // NOTE: uncomment this if you send roles
            // user.Add(new KeyValuePair<string, object>(ClaimTypes.Role, profile.ExtraProperties["roles"]));

            // NOTE: this will set a cookie with all the user claims that will be converted
            //       to a ClaimsPrincipal for each request using the SessionAuthenticationModule HttpModule.
            //       You can choose your own mechanism to keep the user authenticated (FormsAuthentication, Session, etc.)



            //FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(user);


            var ident = new ClaimsIdentity(
                new[]
            {
                new Claim("Certificate", contextCode),

                // populate assigned user's role form your DB
                // and add each one as a claim
                //new Claim(ClaimTypes.Role,"R1"),
                //new Claim(ClaimTypes.Role,"Editor"),
            },
                DefaultAuthenticationTypes.ApplicationCookie);

            if (profile.Gender != null)
            {
                Claim genderClaim = new Claim(ClaimTypes.Gender, profile.Gender);
                ident.AddClaim(genderClaim);
            }
            if (profile.Email != null)
            {
                Claim emailClaim = new Claim(ClaimTypes.Email, profile.Email);
                ident.AddClaim(emailClaim);
            }
            if (profile.FullName != null)
            {
                Claim fullnameCliam = new Claim(ClaimTypes.Name, profile.FullName);
                ident.AddClaim(fullnameCliam);
            }
            if (profile.EmailVerified != null)
            {
                Claim emailVerifiedClaim = new Claim("EmailVerified", profile.EmailVerified.ToString());
                ident.AddClaim(emailVerifiedClaim);
            }
            else
            {
                Claim emailVerifiedClaim = new Claim("EmailVerified", "false");
                ident.AddClaim(emailVerifiedClaim);
            }
            if (token.AccessToken != null)
            {
                Claim auth0Token = new Claim("Auth0Token", token.AccessToken);
                ident.AddClaim(auth0Token);
            }
            if (profile.UserId != null)
            {
                Claim Auth0UserId = new Claim("Auth0UserId", profile.UserId);
                ident.AddClaim(Auth0UserId);
            }

            HttpContext.Current.GetOwinContext().Authentication.SignIn(
                new AuthenticationProperties {
                IsPersistent = false
            }, ident);

            var state = context.Request.QueryString["state"];

            //Take user to passed redirect URL
            if (state != null)
            {
                var stateValues = HttpUtility.ParseQueryString(context.Request.QueryString["state"]);
                var redirectUrl = stateValues["ru"];

                // check for open redirection
                if (redirectUrl != null && IsLocalUrl(redirectUrl))
                {
                    context.Response.Redirect(redirectUrl, true);
                }
            }

            context.Response.Redirect("/");
        }
Ejemplo n.º 21
0
        private async void LoginUser(ANWI.Messaging.LoginRequest cred)
        {
            // Authenticate the user with Auth0
            try {
                // Check version
                if (minimumVersion.CompareTo(cred.clientVer) > 0)
                {
                    logger.Info(
                        $"User {cred.username} has invalid version. " +
                        $"Client: {cred.clientVer} Minimum: {minimumVersion}");
                    DenyLogin(ANWI.Messaging.LoginResponse.Code.FAILED_VERSION);
                    return;
                }

                ResourceOwnerTokenRequest req
                    = new ResourceOwnerTokenRequest()
                    {
                    ClientId     = Configuration.auth0Settings.client,
                    ClientSecret = Configuration.auth0Settings.secret,
                    Realm        = Configuration.auth0Settings.connection,
                    Username     = cred.username,
                    Password     = cred.password
                    };


                AccessTokenResponse token = null;
                try {
                    token = await auth0Client.GetTokenAsync(req);
                } catch (Auth0.Core.Exceptions.ApiException e) {
                    logger.Error(
                        $"Failed to log in user {cred.username}: {e.Message}");
                    DenyLogin(
                        ANWI.Messaging.LoginResponse.Code.FAILED_CREDENTIALS);
                    return;
                }

                UserInfo user
                    = await auth0Client.GetUserInfoAsync(token.AccessToken);

                logger.Info("Successfully authenticated user.  Token: " +
                            token.AccessToken);

                ANWI.AuthenticatedAccount account = new AuthenticatedAccount();
                account.authToken = token.AccessToken;
                account.auth0_id  = user.UserId;
                account.nickname  = user.NickName;

                // Get the main user profile
                Datamodel.User dbUser = null;
                if (!Datamodel.User.FetchByAuth0(ref dbUser, account.auth0_id))
                {
                    logger.Info("Profile not found for user " +
                                account.auth0_id + ". It will be created.");

                    // Create a basic profile
                    if (!CreateDatabaseUser(user.NickName, user.UserId))
                    {
                        DenyLogin(ANWI.Messaging.LoginResponse.
                                  Code.FAILED_SERVER_ERROR);
                        return;
                    }
                }

                account.profile = Profile.FetchByAuth0(account.auth0_id);

                ANWI.Messaging.Message resp = new ANWI.Messaging.Message(
                    0,
                    new ANWI.Messaging.LoginResponse(
                        ANWI.Messaging.LoginResponse.Code.OK,
                        account)
                    );

                SendMessage(resp);
            } catch (System.Net.Http.HttpRequestException e) {
                logger.Info("HTTP error when connecting to Auth0:\n"
                            + e);
                DenyLogin(
                    ANWI.Messaging.LoginResponse.Code.FAILED_SERVER_ERROR);
                return;
            }
        }
Ejemplo n.º 22
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            AuthenticationApiClient client = new AuthenticationApiClient(
                new Uri(string.Format("https://{0}", ConfigurationManager.AppSettings["auth0:Domain"])));

            // IMPORTANT: First Validate the state!
            var stateParam = context.Request.QueryString["state"];
            var state      = AuthHelper.State.Validate(stateParam);
            var code       = context.Request.QueryString["code"];

            if (state == null)
            {
                if (code != null)
                {
                    // Bad State, but good code, may be something nefarious
                    // Force a logout here
                    var baseUrl = context.Request.Url.Scheme + "://" + context.Request.Url.Authority + context.Request.ApplicationPath.TrimEnd('/') + "/";
                    context.Response.Redirect(AuthHelper.Logout(baseUrl));
                    return;
                }
                // Error out if state is no good, or not present
                context.Response.Redirect("/error" + context.Request.Url.Query);
                return;
            }

            var error = context.Request.QueryString["error"];

            if (error != null)
            {
                if (error == "login_required")
                {
                    // Redirect to authorize here and end early
                    // IMPORTANT: force prompt=login here!
                    context.Response.Redirect(AuthHelper.BuildAuthorizeUrl(AuthHelper.Prompt.login, false, state));
                    return;
                }
                else
                {
                    // Some other error
                    context.Response.Redirect("/error" + context.Request.Url.Query);
                    return;
                }
            }

            var token = await client.GetTokenAsync(new AuthorizationCodeTokenRequest
            {
                ClientId     = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                Code         = code,
                RedirectUri  = context.Request.Url.ToString()
            });

            var profile = await client.GetUserInfoAsync(token.AccessToken);

            var user = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("name", profile.FullName ?? profile.PreferredUsername ?? profile.Email),
                new KeyValuePair <string, object>("email", profile.Email),
                new KeyValuePair <string, object>("family_name", profile.LastName),
                new KeyValuePair <string, object>("given_name", profile.FirstName),
                new KeyValuePair <string, object>("nickname", profile.NickName),
                new KeyValuePair <string, object>("picture", profile.Picture),
                new KeyValuePair <string, object>("user_id", profile.UserId),
                new KeyValuePair <string, object>("id_token", token.IdToken),
                new KeyValuePair <string, object>("access_token", token.AccessToken),
                new KeyValuePair <string, object>("refresh_token", token.RefreshToken)
            };

            // NOTE: Uncomment the following code in order to include claims from associated identities
            //profile.Identities.ToList().ForEach(i =>
            //{
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".access_token", i.AccessToken));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".provider", i.Provider));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".user_id", i.UserId));
            //});

            // NOTE: uncomment this if you send roles
            // user.Add(new KeyValuePair<string, object>(ClaimTypes.Role, profile.ExtraProperties["roles"]));

            // NOTE: this will set a cookie with all the user claims that will be converted
            //       to a ClaimsPrincipal for each request using the SessionAuthenticationModule HttpModule.
            //       You can choose your own mechanism to keep the user authenticated (FormsAuthentication, Session, etc.)
            FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(user);

            var returnTo = state.ReturnTo == null ? "/" : state.ReturnTo;

            context.Response.Redirect(returnTo);
        }
Ejemplo n.º 23
0
        public override async Task ProcessRequestAsync(HttpContext context)
        {
            var clientId      = ConfigurationManager.AppSettings["auth0:ClientId"];
            var domain        = $"https://{ConfigurationManager.AppSettings["auth0:Domain"]}";
            var nameSpace     = ConfigurationManager.AppSettings["auth0:ClientNameSpace"];
            var issuer        = $"{domain}/";
            var secret        = ConfigurationManager.AppSettings["auth0:ClientSecret"];
            var auth0Audience = ConfigurationManager.AppSettings["auth0:API"];
            var openIDUrl     = ConfigurationManager.AppSettings["openIDUrl"];

            AuthenticationApiClient client = new AuthenticationApiClient(new Uri(domain));

            var userStr = JsonConvert.SerializeObject(context.User, Formatting.Indented);

            // the code parameter of the returned query string carries the token code.  if that is missing something is wrong at the Auth0 configuration.
            // redirect to the error page.
            var code = context.Request.QueryString["code"];

            if (code == null)
            {
                var errorMessage = "The return Url from Auth0 does not bring back the token code!";
                Debug.WriteLine(errorMessage);
                var path         = "~/Account/Error";          // "Account/Error"; works too
                var redirectUri4 = $"{path}?error={errorMessage}";
                context.Response.Redirect(redirectUri4);
                return;
            }

            var redirectUri = context.Request.Url.ToString();
            var token       = await client.GetTokenAsync(new AuthorizationCodeTokenRequest
            {
                ClientId     = clientId,
                ClientSecret = secret,
                Code         = code,
                RedirectUri  = redirectUri
            });

            try
            {
                // do it only once
                var configurationManager =
                    new ConfigurationManager <OpenIdConnectConfiguration>(openIDUrl,
                                                                          new OpenIdConnectConfigurationRetriever());
                var openIdConfig = AsyncHelper.RunSync(async() =>
                                                       await configurationManager.GetConfigurationAsync(CancellationToken.None));

                var tokenStr = token.IdToken;

                var keySet = openIdConfig?.JsonWebKeySet?.Keys?.FirstOrDefault();
                if (keySet == null)
                {
                    throw new Exception("Unable to Retrieve OpenID Configuration");
                }

                var rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(
                    new RSAParameters()
                {
                    Modulus  = FromBase64Url(keySet.N),
                    Exponent = FromBase64Url(keySet.E)
                });

                var validationParameters = new TokenValidationParameters
                {
                    RequireExpirationTime = true,
                    RequireSignedTokens   = true,
                    ValidAudience         = clientId,
                    ValidateAudience      = true,
                    ValidIssuer           = $"{domain}/",
                    ValidateIssuer        = true,
                    ValidateLifetime      = false,
                    IssuerSigningKey      = new RsaSecurityKey(rsa)
                };

                var handler = new JwtSecurityTokenHandler();
                handler.ValidateToken(tokenStr, validationParameters, out SecurityToken validatedSecurityToken);
                var validatedJwt = validatedSecurityToken as JwtSecurityToken;


                var        aud                   = JsonConvert.SerializeObject(validatedJwt.Audiences, Formatting.Indented);
                var        claims                = JsonConvert.SerializeObject(validatedJwt.Claims, Formatting.Indented);
                var        InnerToken            = JsonConvert.SerializeObject(validatedJwt.InnerToken, Formatting.Indented);
                JwtPayload payload               = validatedJwt.Payload;
                var        payloadStr            = JsonConvert.SerializeObject(payload, Formatting.Indented);
                var        SigningCredentials    = JsonConvert.SerializeObject(validatedJwt.SigningCredentials, Formatting.Indented);
                var        Actor                 = JsonConvert.SerializeObject(validatedJwt.Actor, Formatting.Indented);
                var        EncryptingCredentials = JsonConvert.SerializeObject(validatedJwt.EncryptingCredentials, Formatting.Indented);
                var        ValidFrom             = JsonConvert.SerializeObject(validatedJwt.ValidFrom, Formatting.Indented);
                var        ValidTo               = JsonConvert.SerializeObject(validatedJwt.ValidTo, Formatting.Indented);
                var        EncodedPayload        = JsonConvert.SerializeObject(validatedJwt.EncodedPayload, Formatting.Indented);

                var EncodedHeader           = JsonConvert.SerializeObject(validatedJwt.EncodedHeader, Formatting.Indented);
                var Header                  = JsonConvert.SerializeObject(validatedJwt.Header, Formatting.Indented);
                var Id                      = JsonConvert.SerializeObject(validatedJwt.Id, Formatting.Indented);
                var Issuer                  = JsonConvert.SerializeObject(validatedJwt.Issuer, Formatting.Indented);
                var RawAuthenticationTag    = JsonConvert.SerializeObject(validatedJwt.RawAuthenticationTag, Formatting.Indented);
                var RawCiphertext           = JsonConvert.SerializeObject(validatedJwt.RawCiphertext, Formatting.Indented);
                var RawData                 = JsonConvert.SerializeObject(validatedJwt.RawData, Formatting.Indented);
                var RawEncryptedKey         = JsonConvert.SerializeObject(validatedJwt.RawEncryptedKey, Formatting.Indented);
                var RawHeader               = JsonConvert.SerializeObject(validatedJwt.RawHeader, Formatting.Indented);
                var RawInitializationVector = JsonConvert.SerializeObject(validatedJwt.RawInitializationVector, Formatting.Indented);
                var RawPayload              = JsonConvert.SerializeObject(validatedJwt.RawPayload, Formatting.Indented);
                var RawSignature            = JsonConvert.SerializeObject(validatedJwt.RawSignature, Formatting.Indented);
                var SecurityKey             = JsonConvert.SerializeObject(validatedJwt.SecurityKey, Formatting.Indented);
                var SignatureAlgorithm      = JsonConvert.SerializeObject(validatedJwt.SignatureAlgorithm, Formatting.Indented);
                var Subject                 = JsonConvert.SerializeObject(validatedJwt.Subject, Formatting.Indented);

                // the following property json convert throws exception!
                //var SigningKey= JsonConvert.SerializeObject(validatedJwt.SigningKey, Formatting.Indented);

                var j = 6;
            }
            catch (SecurityTokenExpiredException e)
            {
                Debug.WriteLine("Token has expired");
                Debug.WriteLine($"Error: {e.Message}");
                throw;
            }
            catch (SecurityTokenInvalidSignatureException e)
            {
                Debug.WriteLine("Token has invalid signature");
                Debug.WriteLine($"Error: {e.Message}");
                throw;
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Error occurred while validating token: {e.Message}");
                throw;
            }
            // at this point the token is valid


            var profile = await client.GetUserInfoAsync(token.AccessToken);

            var user = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("name", profile.FullName ?? profile.PreferredUsername ?? profile.Email),
                new KeyValuePair <string, object>("email", profile.Email),
                new KeyValuePair <string, object>("family_name", profile.LastName),
                new KeyValuePair <string, object>("given_name", profile.FirstName),
                new KeyValuePair <string, object>("nickname", profile.NickName),
                new KeyValuePair <string, object>("picture", profile.Picture),
                new KeyValuePair <string, object>("user_id", profile.UserId),
                new KeyValuePair <string, object>("id_token", token.IdToken),
                new KeyValuePair <string, object>("access_token", token.AccessToken),
                new KeyValuePair <string, object>("refresh_token", token.RefreshToken)
            };
            // this point show if SSO is yes


            var additonalClaimInfo = new JObject();

            if (profile.AdditionalClaims.Any())
            {
                var additonalClaims = profile.AdditionalClaims.TryGetValue(nameSpace, out JToken value);
                if (value != null)
                {
                    additonalClaimInfo = (JObject)value;
                    user.Add(new KeyValuePair <string, object>("sso_info", additonalClaimInfo.ToString()));
                }
            }
            // retrieves the rules and attachment to the claim's principal

            Console.Write(additonalClaimInfo.ToString());

            // NOTE: Uncomment the following code in order to include claims from associated identities
            //profile.Identities.ToList().ForEach(i =>
            //{
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".access_token", i.AccessToken));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".provider", i.Provider));
            //    user.Add(new KeyValuePair<string, object>(i.Connection + ".user_id", i.UserId));
            //});

            // NOTE: uncomment this if you send roles
            // user.Add(new KeyValuePair<string, object>(ClaimTypes.Role, profile.ExtraProperties["roles"]));

            // NOTE: this will set a cookie with all the user claims that will be converted
            //       to a ClaimsPrincipal for each request using the SessionAuthenticationModule HttpModule.
            //       You can choose your own mechanism to keep the user authenticated (FormsAuthentication, Session, etc.)
            var isAuthenticated = context.User.Identity.IsAuthenticated;

            FederatedAuthentication.SessionAuthenticationModule.CreateSessionCookie(user);
            isAuthenticated = context.User.Identity.IsAuthenticated;

            var returnTo = "/";
            var state    = context.Request.QueryString["state"];

            if (state != null)
            {
                var stateValues = HttpUtility.ParseQueryString(context.Request.QueryString["state"]);
                var redirectUrl = stateValues["ru"];

                // check for open redirection
                if (redirectUrl != null && IsLocalUrl(redirectUrl))
                {
                    returnTo = redirectUrl;
                }
            }

            context.Response.Redirect(returnTo);
        }