public static IResponseFormatter AuthenticateThisSession(this NancyModule module)
        {
            var code = (string)module.Request.Query["code"];

            var token = Auth0Client.ExchangeCodeForAccessTokenAsync(new ExchangeCodeRequest
            {
                ClientId          = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret      = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                RedirectUri       = ConfigurationManager.AppSettings["auth0:CallbackUrl"],
                AuthorizationCode = code
            }).ConfigureAwait(false).GetAwaiter().GetResult();

            var userInfo = Auth0Client.GetUserInfoAsync(token.AccessToken).ConfigureAwait(false).GetAwaiter().GetResult();

            var user = new Auth0User
            {
                AccessToken  = token.AccessToken,
                UserToken    = token.IdToken,
                UserId       = userInfo.UserId,
                Name         = userInfo.FullName,
                Nickname     = userInfo.NickName,
                GravatarUrl  = userInfo.Picture,
                Email        = userInfo.Email,
                UserMetadata = userInfo.UserMetadata,
                AppMetadata  = userInfo.AppMetadata
            };

            Auth0Authentication.CreateAuthenticationSessionFor(user, module.Context.Request.Session);

            return(module.Response);
        }
예제 #2
0
        public ActionResult Authenticate(Models.AuthenticateModel model, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var result = _client.GetTokenAsync(new ResourceOwnerTokenRequest
                    {
                        ClientId     = Auth0Helper.Auth0ClientId,
                        ClientSecret = Auth0Helper.Auth0ClientSecret,
                        Scope        = "openid profile email",
                        Realm        = Auth0Helper.Connection, // Specify the correct name of your DB connection
                        Username     = model.Email,
                        Password     = model.Password
                    }).Result;

                    // Get user info from token
                    UserInfo user = _client.GetUserInfoAsync(result.AccessToken).Result;
                    if (user.EmailVerified.GetValueOrDefault())
                    {
                        _auth0Helper.Authenticate(user, model.RememberMe, AuthenticationManager);
                        return(RedirectToLocal(returnUrl, model));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Please check your inbox. Your e-mail address need to be verified.");
                    }
                }
                catch (Exception e)
                {
                    HandleAuth0Exception(e);
                }
            }
            return(CurrentUmbracoPage());
        }
예제 #3
0
        public string RegisterProfile(string accessToken, Users user)
        {
            string authDomain = authConfig.Domain;
            AuthenticationApiClient authClient = new AuthenticationApiClient(authDomain);

            UserInfo userInfo = authClient.GetUserInfoAsync(accessToken).Result;

            user.IsSuspended = false;
            user.Usertag     = userInfo.NickName;

            Users dbuser = db.Users.FirstOrDefault(e => e.Usertag == user.Usertag);

            if (dbuser == null)
            {
                db.Attach <Users>(user);
                db.Add <Users>(new Users()
                {
                    FirstName      = user.FirstName,
                    LastName       = user.LastName,
                    Usertag        = user.Usertag,
                    ProfilePicture = user.ProfilePicture,
                    IsSuspended    = false
                });
                db.SaveChanges();
            }
            else
            {
                return(ToJson(new UserComponent(dbuser)));
            }

            ConfigureManagementApi(user, userInfo);
            return(ToJson(new UserComponent(dbuser)));
        }
예제 #4
0
        public ActionResult Login(ContentModel model, string returnUrl = "/", string code = "")
        {
            var loginModel = new Models.LoginModel(model.Content);

            if (!code.IsNullOrEmpty())
            {
                var result = _client.GetTokenAsync(new AuthorizationCodeTokenRequest
                {
                    ClientId     = Auth0Helper.Auth0ClientId,
                    ClientSecret = Auth0Helper.Auth0ClientSecret,
                    Code         = code,
                    RedirectUri  = loginModel.GetRedirectUri()
                }).GetAwaiter().GetResult();


                UserInfo user = _client.GetUserInfoAsync(result.AccessToken).GetAwaiter().GetResult();

                // Authenticate
                _auth0Helper.Authenticate(user, true, AuthenticationManager);

                returnUrl = returnUrl == "/" ? $"/{CurrentUser.LanguageCode}/account/my-profile/" : returnUrl;

                return(RedirectToLocal(returnUrl, loginModel));
            }

            return(CurrentTemplate(loginModel));
        }
예제 #5
0
        public async Task <UserInfo> GetUserInfo()
        {
            var token = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");

            var authApiClient     = new AuthenticationApiClient(_auth0Config.Domain);
            var authenticatedUser = await authApiClient.GetUserInfoAsync(token);

            return(authenticatedUser);
        }
예제 #6
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.ExchangeCodeForAccessTokenAsync(new ExchangeCodeRequest
            {
                ClientId          = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret      = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                AuthorizationCode = 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.UserName ?? 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>("connection", profile.Identities.First().Connection),
                new KeyValuePair <string, object>("provider", profile.Identities.First().Provider)
            };


            // 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);

            if (context.Request.QueryString["state"] != null && context.Request.QueryString["state"].StartsWith("ru="))
            {
                var state = HttpUtility.ParseQueryString(context.Request.QueryString["state"]);
                context.Response.Redirect(state["ru"], true);
            }

            context.Response.Redirect("/hotels");
        }
예제 #7
0
        public async Task <Auth0UserInfo> GetCurrentUserAsync()
        {
            if (!IsCurrentUserAuthorized())
            {
                return(null);
            }

            var apiClient = new AuthenticationApiClient(Config.TenantDomain);
            var user      = await apiClient.GetUserInfoAsync(TokenResponse.AccessToken);

            return(user);
        }
예제 #8
0
        public async Task <object> UserInformation()
        {
            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;

            // If we have an access_token, then retrieve the user's information
            if (!string.IsNullOrEmpty(accessToken))
            {
                return(await _client.GetUserInfoAsync(accessToken));
            }

            return(null);
        }
        public async Task <ActionResult> Login(LoginViewModel vm, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    string auth0Domain       = ConfigurationManager.AppSettings["auth0:Domain"];
                    string auth0ClientId     = ConfigurationManager.AppSettings["auth0:ClientId"];
                    string auth0ClientSecret = ConfigurationManager.AppSettings["auth0:ClientSecret"];

                    AuthenticationApiClient client =
                        new AuthenticationApiClient(
                            new Uri($"https://{auth0Domain}/"));

                    var result = await client.GetTokenAsync(new ResourceOwnerTokenRequest
                    {
                        ClientId     = auth0ClientId,
                        ClientSecret = auth0ClientSecret,
                        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 claimsIdentity = new ClaimsIdentity(new[]
                    {
                        new Claim(ClaimTypes.NameIdentifier, user.UserId, "http://www.w3.org/2001/XMLSchema#string", $"https://{auth0Domain}/"),
                        new Claim(ClaimTypes.Name, user.FullName ?? user.Email, "http://www.w3.org/2001/XMLSchema#string", $"https://{auth0Domain}/"),
                    }, CookieAuthenticationDefaults.AuthenticationType);

                    // Sign user into cookie middleware
                    AuthenticationManager.SignIn(new AuthenticationProperties {
                        IsPersistent = false
                    }, claimsIdentity);

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

            return(View(vm));
        }
예제 #10
0
        //APIController user claim object
        private async Task <UserInfo> UserInformation()
        {
            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;

            // If we have an access_token, then retrieve the user's information
            if (!string.IsNullOrEmpty(accessToken))
            {
                var apiClient = new AuthenticationApiClient(Startup.AuthoDomain);
                var userInfo  = await apiClient.GetUserInfoAsync(accessToken).ConfigureAwait(false);

                return(userInfo);
            }
            return(null);
        }
        public async Task <object> UserInformation()
        {
            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            string accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;

            // If we have an access_token, then retrieve the user's information
            if (!string.IsNullOrEmpty(accessToken))
            {
                var apiClient = new AuthenticationApiClient(_configuration["auth0:domain"]);
                var userInfo  = await apiClient.GetUserInfoAsync(accessToken);

                return(userInfo);
            }

            return(null);
        }
예제 #12
0
        public async Task <IActionResult> Login(LoginViewModel vm, string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var client = new AuthenticationApiClient(new Uri($"https://{_auth0Settings.Domain}/"));

                    var result = await client.GetTokenAsync(new ResourceOwnerTokenRequest
                    {
                        ClientId     = _auth0Settings.ClientId,
                        ClientSecret = _auth0Settings.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);

                    var id       = user.UserId;
                    var username = user.PreferredUsername;
                    var email    = user.Email;


                    // 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("Login", vm));
        }
예제 #13
0
        public async Task Can_obtain_user_info()
        {
            // First get the access token
            var token = await _authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = _connection.Name,
                Username     = _newUser.Email,
                Password     = Password,
                Scope        = "openid profile"
            });

            // Get the user info
            var user = await _authenticationApiClient.GetUserInfoAsync(token.AccessToken);

            user.Should().NotBeNull();
            user.UserId.Should().NotBeNull();
        }
예제 #14
0
        private UserInfo GetUserInformation()
        {
            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            var accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;

            // If we have an access_token, then retrieve the user's information
            if (string.IsNullOrEmpty(accessToken))
            {
                return(null);
            }

            var apiClient = new AuthenticationApiClient(_valueRetrieval.Get("Auth0:Domain"));
            var userInfo  = apiClient.GetUserInfoAsync(accessToken);

            userInfo.Wait();
            var user = userInfo.Result;

            return(user);
        }
예제 #15
0
        public async Task Can_obtain_user_info()
        {
            var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL")));

            // First get the access token
            var token = await authenticationApiClient.GetAccessTokenAsync(new AccessTokenRequest
            {
                ClientId = GetVariable("AUTH0_CLIENT_ID"),
                Connection = "google-oauth2",
                AccessToken = accessToken,
                Scope = "openid"
            });


            // Get the user info
            var user = await authenticationApiClient.GetUserInfoAsync(token.AccessToken);
            user.Should().NotBeNull();
            user.Email.Should().NotBeNull();
        }
예제 #16
0
        public async Task Can_obtain_user_info()
        {
            var authenticationApiClient = new AuthenticationApiClient(new Uri(GetVariable("AUTH0_AUTHENTICATION_API_URL")));

            // First get the access token
            var token = await authenticationApiClient.GetAccessTokenAsync(new AccessTokenRequest
            {
                ClientId    = GetVariable("AUTH0_CLIENT_ID"),
                Connection  = "google-oauth2",
                AccessToken = accessToken,
                Scope       = "openid"
            });


            // Get the user info
            var user = await authenticationApiClient.GetUserInfoAsync(token.AccessToken);

            user.Should().NotBeNull();
            user.Email.Should().NotBeNull();
        }
예제 #17
0
        public static async Task AuthenticationApiMainAsync(string[] args)
        {
            try
            {
                string token = "";

                var handler = new HttpClientHandler
                {
                    Proxy = new WebProxy()
                };
                var api = new AuthenticationApiClient("jerrie.auth0.com");

                var userInfo = await api.GetUserInfoAsync(token);

                Console.WriteLine(userInfo.Email);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
예제 #18
0
        public async Task Can_obtain_user_info()
        {
            var authenticationApiClient = new AuthenticationApiClient(GetVariable("AUTH0_AUTHENTICATION_API_URL"));

            // First get the access token
            var token = await authenticationApiClient.AuthenticateAsync(new AuthenticationRequest
            {
                ClientId     = GetVariable("AUTH0_CLIENT_ID"),
                ClientSecret = GetVariable("AUTH0_CLIENT_SECRET"),
                Realm        = connection.Name,
                Username     = newUser.Email,
                Password     = "******",
                Scope        = "openid profile"
            });

            // Get the user info
            var user = await authenticationApiClient.GetUserInfoAsync(token.AccessToken);

            user.Should().NotBeNull();
            user.UserId.Should().NotBeNull();
        }
예제 #19
0
        public async Task <IActionResult> GetUser()
        {
            IActionResult response = Unauthorized();

            // We're not doing anything with this, but hey! It's useful to know where the user id lives
            var userId = User.Claims.FirstOrDefault(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Value;

            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            var accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;

            // If we have an access_token, then retrieve the user's information
            if (!string.IsNullOrEmpty(accessToken))
            {
                var domain    = _config["Auth0:Domain"];
                var apiClient = new AuthenticationApiClient(domain);
                var userInfo  = await apiClient.GetUserInfoAsync(accessToken);

                return(Ok(userInfo));
            }

            return(response);
        }
예제 #20
0
        public async Task <object> UserInformation()
        {
            // Retrieve the access_token claim which we saved in the OnTokenValidated event
            var accessToken = User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;

            // If we have an access_token, then retrieve the user's information
            try
            {
                if (!string.IsNullOrEmpty(accessToken))
                {
                    var apiClient = new AuthenticationApiClient("https://felipecardozo.auth0.com/");
                    var userInfo  = await apiClient.GetUserInfoAsync(accessToken);

                    return(userInfo);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(null);
        }
        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);
        }
예제 #22
0
    public async Task <ClaimsPrincipal?> Login(LoginViewModel model)
    {
        AccessTokenResponse?result;

        try
        {
            result = await _authenticationApiClient.GetTokenAsync(new ResourceOwnerTokenRequest
            {
                ClientId     = _configuration["AUTH0_CLIENTID"],
                ClientSecret = _configuration["AUTH0_CLIENTSECRET"],
                Scope        = "openid profile",
                Realm        = "Username-Password-Authentication",
                Username     = model.EmailAddress,
                Password     = model.Password
            });
        }
        catch (Exception)
        {
            return(null);
        }

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

        var identity = new ClaimsIdentity(new[]
        {
            new Claim(ClaimTypes.NameIdentifier, user.UserId),
            new Claim(ClaimTypes.Name, user.FullName),
            new Claim("nickname", user.NickName),
            new Claim("picture", user.Picture),
            new Claim("userId", await GetUserId(user.UserId, user.FullName))
        }, CookieAuthenticationDefaults.AuthenticationScheme);

        var claimsPrincipal = new ClaimsPrincipal(identity);

        return(claimsPrincipal);
    }
예제 #23
0
        // TODO: the "Pending" is a poor way to limit the requests to Auth0 API. Very poor!
        public override async Task TokenValidated(TokenValidatedContext ctx)
        {
            var cache = ctx.HttpContext.RequestServices.GetRequiredService <IDistributedCache>();

            var jwt      = (ctx.SecurityToken as JwtSecurityToken);
            var token    = jwt.RawData;
            var cacheKey = $"auth0:userInfo:{token}";
            var cid      = ctx.Principal.Identity as ClaimsIdentity;

            if (_shouldGetRoles() && !_isUnattendedClient(cid))
            {
                CacheEntry cacheEntry = null;
                var        res        = await cache.GetStringAsync(cacheKey);

                if (res == null)
                {
                    var t1 = cache.SetStringAsync(cacheKey, "Pending", new DistributedCacheEntryOptions {
                        AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(5)
                    });

                    var userInfo = await _auth0.GetUserInfoAsync(token);

                    var policyPayload = jwt.Claims.FirstOrDefault(x => x.Type == Auth0ClaimTypes.PolicyPostPayload)?.Value;

                    if (userInfo != null)
                    {
                        cacheEntry = new CacheEntry
                        {
                            UserInfo = userInfo
                        };

                        if (policyPayload != null)
                        {
                            var authzToken = await _getAuthzToken(cache);

                            var url = $"{_authzApiUrl}/api/users/{WebUtility.UrlEncode(userInfo.UserId)}/policy/{WebUtility.UrlEncode(_clientId)}";

                            using (var client = new HttpClient())
                                using (var req = new HttpRequestMessage(HttpMethod.Post, url))
                                {
                                    req.Content = new StringContent(policyPayload, Encoding.UTF8, "application/json");
                                    req.Headers.Add("Authorization", "Bearer " + authzToken);

                                    var policyRes = await client.SendAsync(req);

                                    if (policyRes.IsSuccessStatusCode)
                                    {
                                        var policyJson = await policyRes.Content.ReadAsStringAsync();

                                        var policy = JsonConvert.DeserializeObject <PolicyResult>(policyJson);
                                        if (policy != null)
                                        {
                                            cacheEntry.Policy = policy;
                                        }
                                        else
                                        {
                                            cacheEntry = null;
                                        }
                                    }
                                    else
                                    {
                                        cacheEntry = null;
                                    }
                                }
                        }
                    }

                    await t1;

                    if (cacheEntry != null)
                    {
                        await cache.SetStringAsync(cacheKey, JsonConvert.SerializeObject(cacheEntry), new DistributedCacheEntryOptions
                        {
                            AbsoluteExpiration = jwt.ValidTo - TimeSpan.FromMinutes(2)
                        });
                    }
                    else
                    {
                        await cache.RemoveAsync(cacheKey);
                    }
                }
                else if (res == "Pending")
                {
                    res = await Policy.HandleResult <string>(r => r == "Pending")
                          .WaitAndRetryForeverAsync(x => TimeSpan.FromMilliseconds(100)) // Actually cannot be greater than 5sec as key would expire returning null
                          .ExecuteAsync(() => cache.GetStringAsync(cacheKey))
                    ;
                }

                if (res != null)
                {
                    cacheEntry = JsonConvert.DeserializeObject <CacheEntry>(res);
                }

                if (cacheEntry != null)
                {
                    _convertUserToClaims(cid, cacheEntry);
                }
            }

            // if the identity still doesn't have a name (unattended client) add a name == nameidentifier for logging/metrics purporse
            if (string.IsNullOrWhiteSpace(cid.Name))
            {
                cid.AddClaim(new Claim(cid.NameClaimType, jwt.Subject));
            }

            var scopes = cid.FindFirst(c => c.Type == "scope" && c.Issuer == _issuer)?.Value?.Split(' ');

            if (scopes != null)
            {
                cid.AddClaims(scopes.Select(r => new Claim(Auth0ClaimTypes.Scope, r, ClaimValueTypes.String, _issuer)));
            }

            //if (ctx.Options.SaveToken)
            //    cid.AddClaim(new Claim("id_token", token, ClaimValueTypes.String, "Auth0"));

            await base.TokenValidated(ctx);
        }
예제 #24
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);
        }
예제 #25
0
        public async Task <User> GetAuthenticatedUser()
        {
            if (_authenticatedUser == null)
            {
                if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
                {
                    string accessToken = _httpContextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == "access_token").Value;
                    string userId      = _httpContextAccessor.HttpContext.User.FindFirst(c => c.Type == ClaimTypes.NameIdentifier).Value;

                    if (!string.IsNullOrEmpty(userId) && !string.IsNullOrEmpty(accessToken))
                    {
                        var semaphore = _semaphores.GetOrAdd($"AUTHENTICATED_USER_{userId}", new SemaphoreSlim(1, 1));
                        try
                        {
                            await semaphore.WaitAsync();

                            //Cache user by userId for 5 minutes
                            _authenticatedUser = await _memoryCache.GetOrCreateAsync($"AUTHENTICATED_USER_{userId}", async u =>
                            {
                                var apiClient     = new AuthenticationApiClient(_configuration["Auth0:Domain"]);
                                var userInfo      = apiClient.GetUserInfoAsync(accessToken).Result;
                                var personId      = userInfo.AdditionalClaims["https://login.bcc.no/claims/personId"].ToObject <int?>().GetValueOrDefault();
                                var hasMembership = userInfo.AdditionalClaims["https://login.bcc.no/claims/personId"].ToObject <bool?>().GetValueOrDefault();
                                var churchName    = userInfo.AdditionalClaims["https://login.bcc.no/claims/churchName"]?.ToString() ?? "";

                                //Trying to resolve personKey from provided email address
                                var isAdmin = Administrators.Any(a => a.Equals(userInfo.Email, StringComparison.OrdinalIgnoreCase));

                                var user   = new User();
                                var player = (personId > 0 ? (await _players.GetPlayerByPersonIdAsync(personId)) : null) ?? (await _players.GetPlayerAsync(userInfo.Email));
                                if (!hasMembership || personId == 0)
                                {
                                    if (player != null)
                                    {
                                        await _players.DeletePlayerAsync(player.Id);
                                        user = null;
                                    }
                                }
                                else
                                {
                                    if (player == null || player?.DateRegistered == null)
                                    {
                                        player = new Player {
                                            Email = userInfo.Email, DateRegistered = DateTimeOffset.Now
                                        };
                                    }

                                    var date       = DateTime.Now.AddYears(-18);
                                    var playerDate = DateTime.Parse(userInfo.Birthdate);

                                    player.Name           = userInfo.FullName;
                                    player.NoNbIsStandard = userInfo.Locale == "nb-NO";
                                    player.IsO18          = date > playerDate;
                                    player.Nickname ??= userInfo.FirstName;
                                    player.DateLastActive = DateTimeOffset.Now;
                                    player.PersonId       = personId;
                                    player.Location       = churchName ?? player.Location;

                                    if (player.DiscordId != null)
                                    {
                                        var discordUser = await _discord.SyncUserAsync(player);
                                        if (discordUser?.Id != null)
                                        {
                                            player.DiscordIsConnected = true;
                                            player.DiscordUser        = discordUser.Tag;
                                        }
                                    }
                                    if (player.Email != userInfo.Email)
                                    {
                                        var existingWithSameEmail = await _players.GetPlayerAsync(userInfo.Email);
                                        if (existingWithSameEmail != null)
                                        {
                                            await _players.DeletePlayerAsync(existingWithSameEmail.Id);
                                        }
                                        player.Email = userInfo.Email;
                                    }
                                    player = await _players.SavePlayerAsync(player);
                                    user.InjectFrom(player);
                                    user.CanImpersonate  = isAdmin;
                                    user.IsAdministrator = isAdmin;
                                }

                                u.Priority = CacheItemPriority.High;
                                u.SetAbsoluteExpiration(TimeSpan.FromMinutes(5));


                                return(user);
                            });
                        }
                        finally
                        {
                            semaphore.Release();
                        }
                    }
                }
            }
            return(_authenticatedUser);
        }
예제 #26
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.ExchangeCodeForAccessTokenAsync(new ExchangeCodeRequest
            {
                ClientId          = ConfigurationManager.AppSettings["auth0:ClientId"],
                ClientSecret      = ConfigurationManager.AppSettings["auth0:ClientSecret"],
                AuthorizationCode = context.Request.QueryString["code"],
                RedirectUri       = context.Request.Url.ToString()
            });

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

            string lEmail = "";

            if (profile.Email != null)
            {
                lEmail = profile.Email;
            }

            var user = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("name", profile.UserName ?? lEmail),
                new KeyValuePair <string, object>("email", lEmail),
                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>("connection", profile.Identities.First().Connection),
                new KeyValuePair <string, object>("provider", profile.Identities.First().Provider)
            };

            // 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);
            MySqlConnection dbconn = new MySqlConnection(CommonClass.connectionstring);

            dbconn.Open();


            string lEmailValidated = "0";

            if (profile.EmailVerified == true)
            {
                lEmailValidated = "1";
            }

            UserClass.MigrateUser(dbconn,
                                  profile.UserId,
                                  profile.FullName,
                                  profile.Email,
                                  lEmailValidated
                                  );

            ShoppingCartClass.Swap_Shopping_Cart(dbconn,
                                                 profile.UserId);


            dbconn.Close();


            context.Response.Redirect("~/Account/Validate.aspx");

            //if (lRecords[3] == "3")
            //{
            //   if (lRecords[1] == "1")
            //  {
            //     context.Response.Redirect("~/Account/Manage.aspx");
            //}
            //if (context.Request.QueryString["r_url"] != null)
            //{
            //  if (context.Request.QueryString["r_url"] == "order")
            //{
            //   context.Response.Redirect("~/order_form.aspx");
            //}
            //}
            //context.Response.Redirect("/");
            //}
            //else
            //{
            //    context.Response.Redirect("~/Account/dashboard.aspx");
            //}
        }
예제 #27
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("/");
        }
예제 #28
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);

            JToken emdatSessionKey, shadowsyncurl;

            if (profile.AdditionalClaims.TryGetValue("https://emdat.com/shadowsync/session_key", out emdatSessionKey) &&
                profile.AdditionalClaims.TryGetValue("https://emdat.com/shadowsync/url", out shadowsyncurl))
            {
                string key = emdatSessionKey.ToObject <string>();
                string url = shadowsyncurl.ToObject <string>();
                context.Response.SetCookie(new HttpCookie("ShadowSyncKey", key));
                context.Response.SetCookie(new HttpCookie("ShadowSyncUrl", url));
            }

            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("/");
        }
예제 #29
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);
        }
예제 #30
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;
            }
        }