Пример #1
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;
            string code  = null;
            string state = null;

            try
            {
                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                properties = Options.StateDataFormat.Unprotect(state);

                if (code == null)
                {
                    // Null if the remote server returns an error.
                    return(new AuthenticationTicket(null, properties));
                }

                var body = new Dictionary <string, string> {
                    { "client_id", Options.ClientId },
                    { "redirect_uri", GenerateRedirectUri(properties) },
                    { "client_secret", Options.ClientSecret },
                    { "code", Uri.EscapeDataString(code) },
                    { "grant_type", "authorization_code" }
                };

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(string.Format(TokenEndpoint, Options.Domain), new FormUrlEncodedContent(body), Request.CallCancelled);
                await EnsureTokenExchangeSuccessful(tokenResponse);

                string text = await tokenResponse.Content.ReadAsStringAsync();

                JObject tokens = JObject.Parse(text);

                string accessToken  = tokens["access_token"].Value <string>();
                string idToken      = tokens["id_token"] != null ? tokens["id_token"].Value <string>() : null;
                string refreshToken = tokens["refresh_token"] != null ? tokens["refresh_token"].Value <string>() : null;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    string.Format(UserInfoEndpoint, Options.Domain) + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new Auth0AuthenticatedContext(Context, user, accessToken, idToken, refreshToken);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, ClaimValueTypes.String, context.Connection),
                    new Claim("user_id", context.Id, ClaimValueTypes.String, Constants.Auth0Issuer),

                    new Claim(ClaimTypes.Name, context.Name, ClaimValueTypes.String, context.Connection),
                    new Claim("name", context.Name, ClaimValueTypes.String, context.Connection),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, ClaimValueTypes.String, context.Connection));
                    context.Identity.AddClaim(new Claim("email", context.Email, ClaimValueTypes.String, context.Connection));
                }

                if (!string.IsNullOrWhiteSpace(context.Nickname))
                {
                    context.Identity.AddClaim(new Claim("nickname", context.Nickname, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim("given_name", context.FirstName, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.LastName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.LastName, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Connection))
                {
                    context.Identity.AddClaim(new Claim("connection", context.Connection, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Picture))
                {
                    context.Identity.AddClaim(new Claim("picture", context.Picture, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Provider))
                {
                    context.Identity.AddClaim(new Claim("provider", context.Provider, ClaimValueTypes.String, context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.ProviderAccessToken))
                {
                    context.Identity.AddClaim(new Claim("provider_access_token", context.ProviderAccessToken, ClaimValueTypes.String, context.Connection));
                }

                if (Options.SaveIdToken && !string.IsNullOrWhiteSpace(context.IdToken))
                {
                    context.Identity.AddClaim(new Claim("id_token", context.IdToken, ClaimValueTypes.String, Constants.Auth0Issuer));
                }
                if (Options.SaveRefreshToken && !string.IsNullOrWhiteSpace(context.RefreshToken))
                {
                    context.Identity.AddClaim(new Claim("refresh_token", context.RefreshToken, ClaimValueTypes.String, Constants.Auth0Issuer));
                }
                if (Options.SaveAccessToken && !string.IsNullOrWhiteSpace(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("access_token", context.AccessToken, ClaimValueTypes.String, Constants.Auth0Issuer));
                }

                context.Properties = properties ?? new AuthenticationProperties();

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                var tokenExchangeFailedContext = new Auth0TokenExchangeFailedContext(
                    Context, Options,
                    ex, code, state);
                Options.Provider.TokenExchangeFailed(tokenExchangeFailedContext);

                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Пример #2
0
 /// <summary>
 /// Invoked whenever Auth0 succesfully authenticates a user
 /// </summary>
 /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
 /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
 public virtual Task Authenticated(Auth0AuthenticatedContext context)
 {
     return(OnAuthenticated(context));
 }
 /// <summary>
 /// Invoked whenever Auth0 succesfully authenticates a user
 /// </summary>
 /// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
 /// <returns>A <see cref="Task"/> representing the completed operation.</returns>
 public virtual Task Authenticated(Auth0AuthenticatedContext context)
 {
     return OnAuthenticated(context);
 }
Пример #4
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            AuthenticationProperties properties = null;

            try
            {
                string code  = null;
                string state = null;

                IReadableStringCollection query  = Request.Query;
                IList <string>            values = query.GetValues("code");
                if (values != null && values.Count == 1)
                {
                    code = values[0];
                }
                values = query.GetValues("state");
                if (values != null && values.Count == 1)
                {
                    state = values[0];
                }

                var tokenRequestParameters = string.Format(
                    CultureInfo.InvariantCulture,
                    "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code",
                    Uri.EscapeDataString(Options.ClientId),
                    Uri.EscapeDataString(GenerateRedirectUri()),
                    Uri.EscapeDataString(Options.ClientSecret),
                    code);

                var body = new Dictionary <string, string> {
                    { "client_id", Options.ClientId },
                    { "redirect_uri", GenerateRedirectUri() },
                    { "client_secret", Options.ClientSecret },
                    { "code", Uri.EscapeDataString(code) },
                    { "grant_type", "authorization_code" }
                };

                HttpResponseMessage tokenResponse = await _httpClient.PostAsync(string.Format(TokenEndpoint, Options.Domain), new FormUrlEncodedContent(body), Request.CallCancelled);

                tokenResponse.EnsureSuccessStatusCode();
                string text = await tokenResponse.Content.ReadAsStringAsync();

                JObject tokens = JObject.Parse(text);

                string accessToken = tokens["access_token"].Value <string>();
                string idToken     = tokens["id_token"] != null ? tokens["id_token"].Value <string>() : null;

                HttpResponseMessage graphResponse = await _httpClient.GetAsync(
                    string.Format(UserInfoEndpoint, Options.Domain) + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode();
                text = await graphResponse.Content.ReadAsStringAsync();

                JObject user = JObject.Parse(text);

                var context = new Auth0AuthenticatedContext(Context, user, accessToken, idToken);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", context.Connection),
                    new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", context.Connection),
                    new Claim("user_id", context.Id, "http://www.w3.org/2001/XMLSchema#string", context.Connection),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                if (!string.IsNullOrWhiteSpace(context.Email))
                {
                    context.Identity.AddClaim(new Claim("email", context.Email, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }

                if (!string.IsNullOrWhiteSpace(context.FirstName))
                {
                    context.Identity.AddClaim(new Claim("given_name", context.FirstName, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.LastName))
                {
                    context.Identity.AddClaim(new Claim("family_name", context.LastName, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Connection))
                {
                    context.Identity.AddClaim(new Claim("connection", context.Connection, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Picture))
                {
                    context.Identity.AddClaim(new Claim("picture", context.Picture, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.Provider))
                {
                    context.Identity.AddClaim(new Claim("provider", context.Provider, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (!string.IsNullOrWhiteSpace(context.ProviderAccessToken))
                {
                    context.Identity.AddClaim(new Claim("provider_access_token", context.ProviderAccessToken, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }
                if (Options.SaveIdToken && !string.IsNullOrWhiteSpace(context.IdToken))
                {
                    context.Identity.AddClaim(new Claim("id_token", context.IdToken, "http://www.w3.org/2001/XMLSchema#string", context.Connection));
                }

                context.Properties = properties ?? new AuthenticationProperties();

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                _logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }