C#/ASP.NET Core

[Blazor] Google OAuth 2.0 사용

말하는 닭 2023. 8. 19. 16:21

연동하는 법은 구글에 검색하면 많이 나오니 자세한 내용은 생략한다.

 

Program.cs

options.Events = new OAuthEvents ~~ 부분은 특정 도메인만 OAuth를 할 수 있도록 hd 파라미터를 추가한 부분이다. 특정 도메인만 로그인시키게 하고싶지 않다면 저 부분은 빼도 된다.

builder.Services
	.AddAuthentication(options => {
		options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
		options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
	})
	.AddCookie(options => {
		options.Cookie.IsEssential = true;
	})
	.AddGoogle(options => {
		options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
		options.ClientId = builder.Configuration["Google:client_id"]!;
		options.ClientSecret = builder.Configuration["Google:client_secret"]!;

		// 특정 도메인만 허용하고 싶을 때
		options.Events = new OAuthEvents {
			OnRedirectToAuthorizationEndpoint = context => {
				context.Response.Redirect(context.RedirectUri + "&hd=특정 도메인");
				return Task.FromResult(0);
			}
		};
	});

 

Auth Page

AuthController.cs를 만들어줘서 다음과 같이 작성했다. /login-with-google으로 들어오면 구글 로그인 화면으로 이동한다. 가능하면 .razor로 만들어보고 싶었는데, 하는 방법을 모르겠어서 그냥 인터넷에서 보여주는대로 했다.

[Route("/")]
[ApiController]
public class AuthController : ControllerBase
{
    [HttpGet("login-with-google")]
    public ActionResult LoginWait() {
        var properties = new AuthenticationProperties { RedirectUri = "/auth/google" };
        return Challenge(properties, GoogleDefaults.AuthenticationScheme);
    }
}

 

구글 콘솔에서는 승인된 리디렉션 URI가 /signin-google로 되어있다. 하지만 위 코드에서 RedirectUri는 /auth/google로 되어 있는 것을 볼 수 있다. 둘 다 리디렉션이라고 같은 값으로 두면 안 된다. 이게 헷갈려서 몇 번이나 문제가 생겼는지 모르겠다. 같은 값으로 둘 경우, redirect_uri_mismatch 에러를 볼 수 있다. 

그렇다면 저 "승인된 리디렉션 URI"가 무엇을 의미하는 지는 잘 모르겠다.

 

/login-with-google 로 이동하면 자동으로 흔히 보는 구글 로그인 화면으로 넘어간다. 

만일 NavigationManager를 통해 이동할 경우, forceLoad: true를 꼭 붙여줘야 한다. a 태그는 페이지 이동을 하고 자동으로 리로드를 해주지만 NavigationManager는 forceLoad: ture를 붙여줘야 페이지 이동 후 리로드를 한다. 

private void RedirectToOAuth() {
    NavigationManager.NavigateTo("/login-with-google", forceLoad: true);
}