c#, ASP.net with MVC 5.0 - issue with Google Authentication - c#

I have managed to connect to the GoogleAPi with webforms but am having an issue with MVC.
In theStart.Auth i have put in the following code :
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "6050764343-4ulkmfai2sp2bs.apps.googleusercontent.com",
ClientSecret = "oDBLHfuU9GTqp9Chcz",
CallbackPath = new PathString("/Account/ExternalLoginCallback")
});
getting the following error
The redirect URI in the request, https://localhost:44353/Account/ExternalLoginCallback, does not match the ones authorized for the OAuth client.
i have tried to add to add the following in Route.coinfig with same issue...
//routes.MapRoute(
//name: "signin-google",
//url: "signin-google",
//defaults: new { controller = "Account", action = "ExternalLoginCallback" });
also tried commenting out the line below ...when i added the route map.
CallbackPath = new PathString("/Account/ExternalLoginCallback")
});
Any insight will be greatly appreciated... Thank you

You Can implement Your External Login With Microsoft ASP.NET Identity Samples
And
For External Login You Just Need Add ClientId And ClientSecret. Also See This article Code! MVC 5 App with Facebook, Twitter, LinkedIn and Google OAuth2 Sign-on

i hope this helps anyone who is going round in circles because of not checking the default actionName in my case it was ... ExternalLoginCallback. once i changed that it all worked.!

Related

ASP.NET Core - Preserve POST data after Authorize attribute login redirect

This is essentially the same question as this one:
ASP.NET MVC - Preserve POST data after Authorize attribute login redirect except it isn't asked 7 years ago, and it's about ASP.NET Core, which is pretty different. I am using the [Authorize] attribute to do my most basic access authentication, really just to check to see if there is a user logged in at all. If not, then it kicks them back to the login page. Here's the services setup for that.
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.Name = "loginId";
});
services.ConfigureApplicationCookie(options => options.LoginPath = "/Account/Logout");
Here is my Logout action.
[HttpGet]
[AllowAnonymous]
public async Task<IActionResult> Logout(string returnUrl = "/cgi-s/admin.cgi")
{
await HttpContext.SignOutAsync();
if (HttpContext.Request.Cookies.TryGetValue("loginId", out string loginId))
{
User auth = _context.Users.Where(a => a.LoginId.Equals(loginId)).FirstOrDefault();
if (auth != null)
{
auth.LoginId = string.Empty;
await _context.SaveChangesAsync();
}
}
return Redirect("/Account/Login?returnUrl="+returnUrl);
}
Right now I am just using the default behavior with a return url string to get back to the attempted page after a successful login. Is there a way to set this up so that POST data is also preserved?
I've tried a couple different things, like a custom middleware that stores post data which then gets retrieved on login, but I haven't come up with anything that I haven't found security holes in afterward.
Is there an easy way to do this that I'm just missing?
Thanks.
PS. Please ignore the weirdness going on in the Logout action. We are a two man team working on a 20 year old Perl CGI site, slowly transitioning over to .NET while trying to also keep up with new features and bug fixes, so everything is weird while we run Perl CGI alongside some .NET code on IIS with Postgres. Hopefully we will eventually get everything transitioned over.
Have you tried httpContext.Request.EnableBuffering?
See this question here and be sure to look at the comments: Read the body of a request as string inside middleware
httpContext.Request.EnableBuffering();
using(StreamReader streamReader = new StreamReader(httpContext.Request.Body,
...,leaveOpen: true))
{
//Do something here:
httpContext.Request.Body.Position = 0;
}

How to use IdentityServer4 Access Token and [Authorize] attribute

I have the solution with projects: IdentityServer4, ApiServer, MvcClient. I use Hybrid flow. Auth works very well but I can't get the role in MvcClient.
In the MvсСlient app, after authorization, I get access_token. The token contains the necessary claims. But the MVC application cannot access to the user role.
That is, it is assumed that I will call the external API from the MVC application. But I also need the MVC application to be able to use the user role.
Attribute [Authorize] works fine but [Authorize(Roles =
"admin")] doesn't work!
Source code here: gitlab
Unfortunately, I have not found a better solution than to intercept the Access Token event. Then I parsed it and manually added claims to the cookie.
options.Events = new OpenIdConnectEvents
{
OnTokenResponseReceived = xxx =>
{
JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
JwtSecurityToken jwt = handler.ReadJwtToken(xxx.TokenEndpointResponse.AccessToken);
var claimsIdentity = (ClaimsIdentity) xxx.Principal.Identity;
claimsIdentity.AddClaims(jwt.Claims);
return Task.FromResult(0);
}
};
I will be very grateful to you! If you look at the source code of the project (it has been updated to asp.net core 2.1) and offer the best option!

How to add LinkedIn to SignInManager.GetExternalAuthenticationSchemes()

How do I make a custom authentication provider like LinkedIn appear in SignInManager.GetExternalAuthenticationSchemes() from where Login.cshtml picks up by default
Background Details:
I am trying to understand asp.net core identity framework. In that quest, I created a standard .net core project
I tried out the supported Google authentication alongside reading the documentation and it all worked fine for me.
I was able to make LinkedIn authentication work for me, but couldn't understand how to make certain pieces work. To add support for LinkedIn authentication, I made the following changes
Added the below lines In Startup.Configure method
app.UseOAuthAuthentication(new OAuthOptions() {
AuthenticationScheme = "LinkedIn",
ClientId = Configuration["Authentication:LinkedIn:ClientID"],
ClientSecret = Configuration["Authentication:LinkedIn:ClientSecret"],
CallbackPath = new PathString("/signin-linkedin"),
AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization",
TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken",
UserInformationEndpoint = "https://api.linkedin.com/v1/people/~:(id,formatted-name,email-address,picture-url)",
Scope = { "r_basicprofile", "r_emailaddress" },
});
Added the required ClientId and ClientSecret to the configuration
Added the following line to the Login.cshtml
<button type="submit" class="btn btn-default" name="provider" value="LinkedIn" title="Log in using your LinkedIn account">LinkedIn</button>
All this works fine. Now my question is:
For supported authentication providers, as soon as I call, say, app.UseGoogleAuthentication in Startup.Configure, my call to SignInManager.GetExternalAuthenticationSchemes() in Login.cshtml lists Google as a provider. What do I need to do, so the call to SignInManager.GetExternalAuthenticationSchemes() will also list LinkedIn as a provider
What do I need to do, so the call to SignInManager.GetExternalAuthenticationSchemes() will also list LinkedIn as a provider
This method only lists the authentication middleware that have been assigned a "display name".
To include Linked in the providers list, set OAuthOptions.DisplayName:
app.UseOAuthAuthentication(new OAuthOptions
{
DisplayName = "LinkedIn"
// ...
});

Redirect URI with Google using asp.net MVC

I'm trying to use oauth with Google in ASP.NET MVC 5.
In Google's developer console I put for the redirect uri:
www.mydomain.com/account/externallogincallback
and thought that this will do. But it didn't.
I put:
www.mydomain.com/signin-google
and it worked!
I tried to search the string "signin-google" in my project but couldn't find it anywhere.
Can someone tell me what is going on? why is that so? thanks.
I am too lazy to write a properly formatted answer, I placed these comments in code for myself to remember how to resolve this issue. It is not really an issue, just something I never bothered to read properly :) But this is what you can do to make it work. There 2 options how you can do it. I have tried both and both options work just fine. I went with the first one for now, it really doesnt matter. Here are my comments in Startup.Auth.cs file.
// My notes to resolve Google Error: redirect_uri_mismatch error
// By default GoogleOAuth2AuthenticationOptions has CallbackPath defined as "/signin-google"
// https://msdn.microsoft.com/en-us/library/microsoft.owin.security.google.googleoauth2authenticationoptions(v=vs.113).aspx
// But the real path should be Controller/Action: for this application it is "/Account/ExternalLoginCallback"
// There are 2 ways to define it properly:
// 1) Add a new route in RouteConfig.cs that will map "/signin-google" into "/Account/ExternalLoginCallback":
// routes.MapRoute(name: "signin-google", url: "signin-google", defaults: new { controller = "Account", action = "ExternalLoginCallback" });
// Remember, in Google Developers Console you must have your "/signin-google" redirect URI, since that is what your app sends to Google
// 2) Completely overwrite built-in "/signin-google" path.
// Owerwrite CallbackPath right here by adding this line after ClientSecret:
// CallbackPath = new PathString("/Account/ExternalLoginCallback")
// Remember, in Google Developers Console you must have "/Account/ExternalLoginCallback" redirect URI, since now that is what your app sends to Google
app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
{
ClientId = "xxxxxxxxxxxxxxxxxxxx",
ClientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx"
});

External Authentication not redirecting to external site

Have a weird thing happening here.
I have built an ASP.NET MVC5 website, and have local accounts working fine via ASP.NET Identity.
I am now trying to enable external authentication, but have some weirdness happening.
I'm certain I've followed the right steps. I have this in my Startup.Auth.cs:
public void ConfigureAuth(IAppBuilder app)
{
// Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
// Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
// clientId: "",
// clientSecret: "");
//app.UseTwitterAuthentication(
// consumerKey: "",
// consumerSecret: "");
//app.UseFacebookAuthentication(
// appId: "",
// appSecret: "");
app.UseGoogleAuthentication();
}
When the user clicks on the link to logon with Google, the ExternalLogin method is called:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
Which I have verified via debugging gets into the ExecuteResult method of the ChallengeResult class:
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties() { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
However, in the browser, nothing happens. I just get a blank page where I would expect a redirect to the Google signin page.
There are no errors reported at all.
The other funny thing is that I tried to create another MVC5 application, but I get a "Object reference not set to an instance of an object" popup in VS2013, and the resultant project is missing the Account controller that is usually there by default.
I've repaired the installation of VS2013, I have re-installed Update 1, and I've also updated all Nuget packages in the solution.
I've run out of ideas of where to go next.
Update 1
Thinking that this may be related to my PC, I've deployed the website to Azure, and the problem still persists. Does this mean it could be related to a missing assembly, and it's not being reported correctly?
I've run fusionlog, but I see no binding failures.
Spinning up a new VM with a clean install of Windows 8 and VS2013 to see if I can get a new project working there.
Update 2
Ok, just ran another round of "network" capturing, and when the user selects the external provider, it DOES post to the ExternalLogin action, but the response is a 401 Unauthorized. What could be causing this?
Ok,
I figured out what (the important part) of the issue was.
Firstly, I still don't known why when I create an MVC project I don't get a scaffold'ed AccountController class.
However, it seems my issue is that my login button was passing "google" instead of "Google" as the provider.
Seriously!? I am a little surprised that casing would matter with the name of the provider, but there you go.
This is not the answer to your question but it respond a very similar problem
If you had Owin 2.0 and you migrate to 2.1
The _ExternalLoginsListPartial need to change from this:
<button type="submit" class="btn btn-default" id="#p.AuthenticationType" name="Partner" value="#p.AuthenticationType" title="Log in using your #p.Caption account">#p.AuthenticationType</button>
to this
<button type="submit" class="btn btn-default" id="#p.AuthenticationType" name="provider" value="#p.AuthenticationType" title="Log in using your #p.Caption account">#p.AuthenticationType</button>
The only thing that change is the name of the button but that could break your head like mine and cost me 2 days of work to find the problem.
Maybe this is explained in the new Owin version, if not must be something to specify in capitals.
I've just ran into the same issue with my ASP.Net WebAPI server. I was passing the correct AuthenticationType into the challenge method but still getting a blank page.
Turns out the issue was the order I added the OAuth providers into the OWIN pipeline at startup.
Roughly my working order:
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
OAuthBearerOptions = new OAuthBearerAuthenticationOptions();
var authServerOptions = new OAuthAuthorizationServerOptions
{
...
};
// Token Generation
app.UseOAuthAuthorizationServer(authServerOptions);
app.UseOAuthBearerAuthentication(OAuthBearerOptions);
// Configure Google External Login
GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions()
{
ClientId = xxxx,
ClientSecret = xxxx,
Provider = new GoogleAuthProvider()
};
app.UseGoogleAuthentication(GoogleAuthOptions);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
Previously I was adding the UseCors + UseWebApi methods before UseGoogleAuthentication method.
I found this post to be useful too:
http://coding.abel.nu/2014/06/understanding-the-owin-external-authentication-pipeline/

Categories

Resources