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]; } if (!ValidateStateId(state, out properties)) { 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>("appid", Options.AppId), new KeyValuePair <string, string>("secret", Options.AppSecret), new KeyValuePair <string, string>("code", code), new KeyValuePair <string, string>("grant_type", "authorization_code"), }; var requestContent = new FormUrlEncodedContent(tokenRequestParameters); // 通过code获取access_token HttpResponseMessage response = await _httpClient.PostAsync(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 openId = oauth2Token.Value <string>("openid"); var scope = oauth2Token.Value <string>("scope"); var unionId = oauth2Token.Value <string>("unionid"); // 获取用户信息 var userInfoResponse = await _httpClient.GetAsync(string.Format(UserInfoEndpoint + "?access_token={0}&openid={1}", Uri.EscapeDataString(accessToken), Uri.EscapeDataString(openId)), Request.CallCancelled); userInfoResponse.EnsureSuccessStatusCode(); string userInfoResponseString = await userInfoResponse.Content.ReadAsStringAsync(); JObject userInformation = JObject.Parse(userInfoResponseString); _logger.WriteInformation(userInfoResponseString); var context = new WeixinAuthenticatedContext(Context, userInformation, accessToken, refreshToken, expire); context.Identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, WeixinSecurityConstants.DefaultAuthenticationType, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.Surname, context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(ClaimTypes.NameIdentifier, context.OpenId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(CommonClaimType.NickName, context.Nickame, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(CommonClaimType.Avatar, context.HeadimgUrl, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), new Claim(WeixinSecurityConstants.WeixinClaimType, userInformation.ToString(), "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), }, Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); 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)); } }
///// <summary> ///// Called when a Challenge causes a redirect to authorize endpoint ///// </summary> //public void ApplyRedirect(WeixinApplyRedirectContext context) //{ // OnApplyRedirect(context); //} /// <summary> /// Invoked whenever succesfully authenticates a user /// </summary> public Task Authenticated(WeixinAuthenticatedContext context) { return(OnAuthenticated(context)); }