Esempio n. 1
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];
                }

                properties = Options.StateDataFormat.Unprotect(state);
                if (properties == null)
                {
                    return(null);
                }

                // OAuth2 10.12 CSRF
                if (!ValidateCorrelationId(properties, logger))
                {
                    return(new AuthenticationTicket(null, properties));
                }

                string requestPrefix = Request.Scheme + "://" + Request.Host;
                string redirectUri   = requestPrefix + Request.PathBase + Options.CallbackPath;

                // Build up the body for the token request
                var body = new List <KeyValuePair <string, string> >();
                body.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
                body.Add(new KeyValuePair <string, string>("code", code));
                body.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
                body.Add(new KeyValuePair <string, string>("state", state));
                body.Add(new KeyValuePair <string, string>("scope", string.Join(",", Options.Scope)));
                var request = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
                request.Content = new FormUrlEncodedContent(body);

                // Request the token

                HttpResponseMessage tokenResponse =
                    await httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));

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

                // Deserializes the token response
                dynamic response     = JsonConvert.DeserializeObject <dynamic>(text);
                string  accessToken  = (string)response.access_token;
                string  expires      = (string)response.expires_in;
                string  refreshToken = (string)response.refresh_token;

                // Get the Reddit user
                HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
                userRequest.Headers.Add("User-Agent", "OWIN OAuth Provider");
                userRequest.Headers.Add("Authorization", "bearer " + Uri.EscapeDataString(accessToken) + "");
                HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);

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

                JObject user = JObject.Parse(text);

                var context = new RedditAuthenticatedContext(Context, user, accessToken, expires, refreshToken);
                context.Identity = new ClaimsIdentity(
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);
                if (!string.IsNullOrEmpty(context.Id))
                {
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.UserName))
                {
                    context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.Link))
                {
                    context.Identity.AddClaim(new Claim("urn:reddit:url", context.Link, XmlSchemaString, Options.AuthenticationType));
                }
                if (!string.IsNullOrEmpty(context.AccessToken))
                {
                    context.Identity.AddClaim(new Claim("urn:reddit:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType));
                }
                context.Identity.AddClaim(new Claim("urn:reddit:overeighteen", context.OverEighteen.ToString()));
                context.Properties = properties;

                await Options.Provider.Authenticated(context);

                return(new AuthenticationTicket(context.Identity, context.Properties));
            }
            catch (Exception ex)
            {
                logger.WriteError(ex.Message);
            }
            return(new AuthenticationTicket(null, properties));
        }
Esempio n. 2
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync( )
        {
            _logger.WriteVerbose("AuthenticateCoreAsync");

            AuthenticationProperties properties = null;

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

                var query  = Request.Query;
                var 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 (properties == null)
                {
                    return(null);
                }

                var redirectUri = string.Format("{0}://{1}{2}{3}",
                                                Request.Scheme, Request.Host, RequestPathBase, Options.ReturnEndpointPath);
                var scopes = string.Join(" ", Options.Scope);

                var tokenRequestParameters = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("client_id", Options.ClientId),
                    new KeyValuePair <string, string>("client_secret", Options.ClientSecret),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri),
                    new KeyValuePair <string, string>("scope", scopes),
                };

                var requestContent = new FormUrlEncodedContent(tokenRequestParameters);
                _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", "{0}:{1}".With(Options.ClientId, Options.ClientSecret).ToBase64String( ));

                var response =
                    await _httpClient.PostAsync(TokenUri, requestContent, Request.CallCancelled);

                response.EnsureSuccessStatusCode( );
                var oauthTokenResponse = await response.Content.ReadAsStringAsync( );

                var oauth2Token = ParseTokenResponse(oauthTokenResponse);

                var accessToken = oauth2Token["access_token"];

                if (string.IsNullOrWhiteSpace(accessToken))
                {
                    _logger.WriteWarning("Access token was not found");
                    return(new AuthenticationTicket(null, properties));
                }

                var testUri = AccountUri + "?access_token=" + Uri.EscapeDataString(accessToken) +
                              "&oauth_token=" + Options.ClientSecret + "&oauth_consumer_key=" + Options.ClientId;
                _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", accessToken);
                var graphResponse = await _httpClient.GetAsync(testUri, Request.CallCancelled);

                graphResponse.EnsureSuccessStatusCode( );
                var accountString = await graphResponse.Content.ReadAsStringAsync( );

                var accountInformation = JObject.Parse(accountString);

                var context = new RedditAuthenticatedContext(Context, accountInformation, accessToken);
                context.Identity = new ClaimsIdentity(
                    new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, context.Id, Schema, Options.AuthenticationType),
                    new Claim(ClaimTypes.Name, context.Username, Schema, Options.AuthenticationType),

                    new Claim("urn:reddit:id", context.Id, Schema, Options.AuthenticationType),
                    new Claim("urn:reddit:name", context.Username, Schema, Options.AuthenticationType),
                },
                    Options.AuthenticationType,
                    ClaimsIdentity.DefaultNameClaimType,
                    ClaimsIdentity.DefaultRoleClaimType);

                await Options.Provider.Authenticated(context);

                properties.RedirectUri = RedditAuthenticationHandler.ReturnUri;
                context.Properties     = properties;

                return(new AuthenticationTicket(context.Identity, context.Properties));
            } catch (Exception ex) {
                _logger.WriteWarning("Authentication failed", ex);
                return(new AuthenticationTicket(null, properties));
            }
        }