/// <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(SimpleSSOAccountAuthenticatedContext context) { return(OnAuthenticated(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(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)); } _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); HttpResponseMessage graphResponse = await _httpClient.GetAsync( Options.UserInformationEndpoint); graphResponse.EnsureSuccessStatusCode(); string accountString = await graphResponse.Content.ReadAsStringAsync(); JObject accountInformation = JObject.Parse(accountString); var context = new SimpleSSOAccountAuthenticatedContext(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:simplesso:id", context.Id, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("urn:simplesso: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.Properties = properties; return(new AuthenticationTicket(context.Identity, context.Properties)); } catch (Exception ex) { _logger.WriteError("Authentication failed", ex); return(new AuthenticationTicket(null, properties)); } }