Hello,
I’m having trouble figuring out how to authenticate with my .net controller using fetch from my react component.
I’m using .net core with react / redux for my project. I’ve configured my authentication using the okta sign in + .net core server steps outlined here.
I tried using the react widget outlined here but it doesn’t currently support server side rendering.
I tried using the react setup outlined here but had trouble figuring out how to use MFA workflows. I’m assuming this is the only way to solve this problem, in which case i’ll need to do more digging on how to setup my own MFA flow.
I’ve outlined a snippet of my setup below that uses the okta sign in page + .net core method. Calling fetch on GetMyEmail fails because its not authenticated. I’m hoping there is a easy way to handle this.
//Controller
[Authorize]
[HttpGet("[action]")]
public string GetMyEmail()
{
return User.Claims
.FirstOrDefault(x => x.Type == “preferred_username”)
?.Value.ToString();
}
//React
async componentDidMount() {
try {
const response = await fetch(‘api/Okta/GetMyEmail’,
{
//How do I Authenticate here?
//How do i get the token to authenticate?
});
const data = await response.json();
console.log('email ', data)
} catch (err) {
// handle error as needed
console.log(err)
}
}
//Okta auth init
services.AddAuthentication(sharedOptions =>
{
sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.ClientId = “{secret}”;
options.ClientSecret = “{secret}”;
options.Authority = “https://{myoktadomain}.com/oauth2/default”;
options.CallbackPath = “/authorization-code/callback”;
options.ResponseType = “code”;
options.SaveTokens = true;
options.UseTokenLifetime = false;
options.GetClaimsFromUserInfoEndpoint = true;
options.Scope.Add(“openid”);
options.Scope.Add(“profile”);
options.TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = “name”
};
});