public override Task Authenticated(MicrosoftAccountAuthenticatedContext context) { string avatarUrl = string.Format("https://apis.live.net/v5.0/{0}/picture", context.User.GetValue("id").ToString()); context.Identity.AddClaim( new Claim(OwinHelper.ClaimTypeAvatarUrl, avatarUrl)); return base.Authenticated(context); }
public override Task Authenticated(MicrosoftAccountAuthenticatedContext context) { context.Identity.AddClaim(new Claim(Claims.ExternalAccessToken, context.AccessToken)); context.Identity.AddClaim(new Claim(Claims.ExternalUserName, context.Name)); if (context.ExpiresIn.HasValue) { context.Identity.AddClaim(new Claim(Claims.ExternalExpiresIn, context.ExpiresIn.ToString())); } return base.Authenticated(context); }
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(Options.CookieManager, properties, _logger)) { return(new AuthenticationTicket(null, properties)); } var tokenRequestParameters = new List <KeyValuePair <string, string> >() { new KeyValuePair <string, string>("client_id", Options.ClientId), new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()), new KeyValuePair <string, string>("client_secret", Options.ClientSecret), new KeyValuePair <string, string>("code", code), new KeyValuePair <string, string>("grant_type", "authorization_code"), }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); HttpResponseMessage response = await _httpClient.PostAsync(Options.TokenEndpoint, requestContent, Request.CallCancelled); response.EnsureSuccessStatusCode(); string oauthTokenResponse = await response.Content.ReadAsStringAsync(); JObject oauth2Token = JObject.Parse(oauthTokenResponse); var accessToken = oauth2Token["access_token"].Value <string>(); // Refresh token is only available when wl.offline_access is request. // Otherwise, it is null. var refreshToken = oauth2Token.Value <string>("refresh_token"); var expire = oauth2Token.Value <string>("expires_in"); if (string.IsNullOrWhiteSpace(accessToken)) { _logger.WriteWarning("Access token was not found"); return(new AuthenticationTicket(null, properties)); } var graphRequest = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint); graphRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var graphResponse = await _httpClient.SendAsync(graphRequest, Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); string accountString = await graphResponse.Content.ReadAsStringAsync(); JObject accountInformation = JObject.Parse(accountString); var context = new MicrosoftAccountAuthenticatedContext(Context, accountInformation, accessToken, refreshToken, expire); context.Identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:microsoftaccount:id", context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:microsoftaccount:name", context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType) }, Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrWhiteSpace(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }
protected override async Task <AuthenticationTicket> AuthenticateCore() { _logger.WriteVerbose("AuthenticateCore"); AuthenticationExtra extra = null; try { string code = null; string state = null; IDictionary <string, string[]> query = Request.GetQuery(); string[] values; if (query.TryGetValue("code", out values) && values != null && values.Length == 1) { code = values[0]; } if (query.TryGetValue("state", out values) && values != null && values.Length == 1) { state = values[0]; } extra = Options.StateDataHandler.Unprotect(state); if (extra == null) { return(null); } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(extra, _logger)) { return(new AuthenticationTicket(null, extra)); } 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); WebRequest tokenRequest = WebRequest.Create(TokenEndpoint); tokenRequest.Method = "POST"; tokenRequest.ContentType = "application/x-www-form-urlencoded"; tokenRequest.ContentLength = tokenRequestParameters.Length; tokenRequest.Timeout = Options.BackChannelRequestTimeOut; using (var bodyStream = new StreamWriter(tokenRequest.GetRequestStream())) { bodyStream.Write(tokenRequestParameters); } WebResponse tokenResponse = await tokenRequest.GetResponseAsync(); string accessToken = null; using (var reader = new StreamReader(tokenResponse.GetResponseStream())) { string oauthTokenResponse = await reader.ReadToEndAsync(); JObject oauth2Token = JObject.Parse(oauthTokenResponse); accessToken = oauth2Token["access_token"].Value <string>(); } if (string.IsNullOrWhiteSpace(accessToken)) { _logger.WriteWarning("Access token was not found"); return(new AuthenticationTicket(null, extra)); } JObject accountInformation; var accountInformationRequest = WebRequest.Create(GraphApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken)); accountInformationRequest.Timeout = Options.BackChannelRequestTimeOut; var accountInformationResponse = await accountInformationRequest.GetResponseAsync(); using (var reader = new StreamReader(accountInformationResponse.GetResponseStream())) { accountInformation = JObject.Parse(await reader.ReadToEndAsync()); } var context = new MicrosoftAccountAuthenticatedContext(Request.Environment, accountInformation, accessToken); context.Identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.NameIdentifier, context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.Name, context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:microsoftaccount:id", context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:microsoftaccount:name", context.Name, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), }, Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrWhiteSpace(context.Email)) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType)); } await Options.Provider.Authenticated(context); context.Extra = extra; return(new AuthenticationTicket(context.Identity, context.Extra)); } catch (Exception ex) { _logger.WriteWarning("Authentication failed", ex); return(new AuthenticationTicket(null, extra)); } }
/// <summary> /// Invoked whenever Microsoft 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(MicrosoftAccountAuthenticatedContext context) { return(OnAuthenticated(context)); }
/// <summary> /// Invoked whenever Microsoft 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(MicrosoftAccountAuthenticatedContext context) { return OnAuthenticated(context); }