I'm new to Oauth2 with .Net and I am trying to get it to work. I've tried editing the Program.Cs but it hasn't worked.
Program.Cs
builder.Services.AddAuthentication(options => {
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/users/google/login";
})
.AddGoogle(options =>
{
options.ClientId = builder.Configuration.GetSection("GoogleOauthSettings:ClientId").Value;
options.ClientSecret = builder.Configuration.GetSection("GoogleOauthSettings:ClientSecret").Value;
});
My Users Controller Routes. To save space I am not adding my other routes since all of those work. I am just showing my imports and google routes.
using Microsoft.AspNetCore.Mvc;
using CalenTaskApi.Respositories;
using CalenTaskApi.Dtos;
using CalenTaskApi.Entities;
using System.Text;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using CalenTaskApi.Service;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Google;
using Microsoft.AspNetCore.Authentication.Cookies;
using Newtonsoft.Json;
[HttpPost("google/login")]
public IActionResult LoginWithGoogle(GoogleLoginDto googleLoginDto)
{
var properties = new AuthenticationProperties { RedirectUri = Url.Action("GoogleResponse") };
return Challenge(properties, GoogleDefaults.AuthenticationScheme);
}
[HttpPost("google/response")]
public async Task<string> GoogleResponse()
{
var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
var claims = result.Principal.Identities
.FirstOrDefault().Claims.Select(claim => new
{
claim.Issuer,
claim.OriginalIssuer,
claim.Type,
claim.Value
});
var claimsJson = JsonConvert.SerializeObject(claims);
return claimsJson;
}
C# is telling me that the google/response router in my var claims the result.Principal.Indentities is returning null.