안녕하세요, 내 기본 MVC5 응용 프로그램에서 Google 연락처를 검색하고 싶습니다. 아래 코드를 사용하여 성공적으로 로그인합니다. 내가 지금은 구글의 연락처를 검색 할 구글 자격 증명을 사용하여 loged하고 때 인증 확인시Google 연락처 가져 오기
GoogleOAuth2AuthenticationOptions googleOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = "<ClientId>",
ClientSecret = "<ClientSecret>",
AccessType = "offline",
Provider = new GoogleOAuth2AuthenticationProvider()
{
OnAuthenticated = (context) =>
{
context.Identity.AddClaim(new Claim("accessToken", context.AccessToken))
if (context.RefreshToken != null)
{
context.Identity.AddClaim(new Claim("refreshToken", context.RefreshToken));
}
context.Identity.AddClaim(new Claim("EmailAddressFieldName", context.Email));
context.Identity.AddClaim(new Claim("NameFieldName", context.Name));
context.Identity.AddClaim(new Claim("TokenIssuedFieldName", DateTime.Now.ToString()));
context.Identity.AddClaim(new Claim("TokenExpiresInFieldName",
((long)context.ExpiresIn.Value.TotalSeconds).ToString()));
return Task.FromResult(0);
}
}
};
//googleOptions.Scope.Add("https://www.google.com/m8/feeds");
app.UseGoogleAuthentication(googleOptions);
나는
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
//one things to be noted is when i use googleOptions.Scope.Add("https://www.google.com/m8/feeds"); as commented above this info is null
//not sure why
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
var accessToken = info.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "accessToken");
var refreshToken = info.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == "refreshToken");
await UserManager.AddClaimAsync(user.Id, accessToken);
await UserManager.AddClaimAsync(user.Id, refreshToken);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
어쨌든 계정 컨트롤러 내 callbackmethod에 ASPNetUserClaims 테이블에 내 AccessToken과 RefreshToken을 저장 ContactsContact의 HomeController 아래 코드와 같이 Google 클라이언트 라이브러리 사용하기.
public ActionResult Contact()
{
var user= UserManager.FindByEmailAsync(User.Identity.Name);
var claim = ClaimsPrincipal.Current.Claims;
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = claim.Where(i => i.Type == "accessToken").Select(i => i.Value).SingleOrDefault();
parameters.RefreshToken = claim.Where(i => i.Type == "refreshToken").Select(i => i.Value).SingleOrDefault();
//parameters.Scope = "https://www.google.com/m8/feeds";
GetGoogleContacts(parameters);
return View();
}
private static void GetGoogleContacts(OAuth2Parameters parameters)
{
try {
RequestSettings settings = new RequestSettings("MvcAuth",parameters);
ContactsRequest cr = new ContactsRequest(settings);
Feed<Contact> f = cr.GetContacts();
foreach (Contact c in f.Entries)
{
Console.WriteLine(c.Name.FullName);
}
}
catch (Exception a)
{
Console.WriteLine("A Google Apps error occurred.");
Console.WriteLine();
}
}
는하지만 예외 을 얻을 "요청의 실행 실패 : https://www.google.com/m8/feeds/contacts/default/full": (401) 무단 원격 서버에서 오류를 반환했습니다. 그 이유가 유효하지 않은 경우 나의 accesstoken이 유효하지 않음을 의미합니다. 어떻게 내 Google 연락처를 얻을 수 있습니다. 제발 내가 거의 5 일 그것을 에 썼다는 것을 돕는다. 그러나 성공하지 못했다. 난 그냥 당신이 토큰 & Refersh 토큰 cliam 테이블에 저장되어있는 ACESS가, 둘째, 당신은 액세스 토큰을 알고 있어야합니다 확인해야합니다 내가 Owin 미들웨어 구성 요소 UseGoogleAuthentication()
연락처 연락처 액세스 토큰은 어떻게 신청하고 있습니까? – DaImTo
ContactsRequest 용 .Net Client Library를 사용하고 있습니다. https://developers.google.com/google-apps/contacts/v3/ 아래 링크를 참조하십시오. OAuth2Parameters로 accessToken을 전달합니다. –
실제로이 자습서 http : //를 따르고 있습니다. www.daimto.com/google-contacts-with-c/하지만 owin middleware 구성 요소 usegoogleauthentication()을 사용하여 성공적으로 인증되면 외부 콜백 fuction에 저장된 Aspnet 클레임에서 accessToken을 얻고 있습니다 –