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>("appid", Options.AppId), new KeyValuePair <string, string>("redirect_uri", GenerateRedirectUri()), new KeyValuePair <string, string>("secret", Options.AppSecret), new KeyValuePair <string, string>("code", code), new KeyValuePair <string, string>("grant_type", "authorization_code"), }; var queryString = tokenRequestParameters.Aggregate("", (current, tokenRequestParameter) => current + (tokenRequestParameter.Key + "=" + tokenRequestParameter.Value + "&")); queryString = queryString.Remove(queryString.Length - 1, 1); HttpResponseMessage response = await _httpClient.GetAsync(Options.TokenEndpoint + "?" + queryString); response.EnsureSuccessStatusCode(); var oauthTokenResponse = await response.Content.ReadAsStringAsync(); JObject oauth2Token = JObject.Parse(oauthTokenResponse); var accessToken = oauth2Token.Value <string>("access_token"); var refreshToken = oauth2Token.Value <string>("refresh_token"); var expire = oauth2Token.Value <string>("expires_in"); var scope = oauth2Token.Value <string>("scope"); var openId = oauth2Token.Value <string>("openid"); var unionId = oauth2Token.Value <string>("unionid"); if (string.IsNullOrWhiteSpace(accessToken)) { _logger.WriteWarning("Access token was not found"); return(new AuthenticationTicket(null, properties)); } #region Get UserInfo var graphRequest = new HttpRequestMessage(HttpMethod.Get, Options.UserInformationEndpoint + $"?access_token={accessToken}&openid={openId}"); var graphResponse = await _httpClient.SendAsync(graphRequest, Request.CallCancelled); graphResponse.EnsureSuccessStatusCode(); string accountString = await graphResponse.Content.ReadAsStringAsync(); JObject accountInformation = JObject.Parse(accountString); var errcode = accountInformation.Value <string>("errcode"); if (!string.IsNullOrWhiteSpace(errcode)) { var errmsg = accountInformation.Value <string>("errmsg"); _logger.WriteWarning(errmsg); return(new AuthenticationTicket(null, properties)); } #endregion var context = new WeChatAccountAuthenticatedContext(Context, accountInformation, accessToken, refreshToken, expire); context.Identity = new ClaimsIdentity( new[] { new Claim(ClaimTypes.NameIdentifier, context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.Name, context.NickName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:openid", context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:nickname", context.NickName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:sex", context.Sex, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:headimgurl", context.HeadImgUrl, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:country", context.Country, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:province", context.Province, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("wechataccount:city", context.City, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("qqaccount:unionid", context.UnionId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim("qqaccount:privilege", context.Privilege, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), }, Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); 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)); } }
/// <summary> /// Invoked whenever WeChat 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(WeChatAccountAuthenticatedContext context) { return(OnAuthenticated(context)); }