Giter Site home page Giter Site logo

aspnet-contrib / aspnet.security.openid.providers Goto Github PK

View Code? Open in Web Editor NEW
218.0 14.0 39.0 1.09 MB

OpenID 2.0 authentication middleware for ASP.NET Core

License: Apache License 2.0

Batchfile 0.13% Shell 29.27% C# 25.46% PowerShell 41.60% CMake 3.55%
aspnetcore openid social-authentication

aspnet.security.openid.providers's Introduction

AspNet.Security.OpenId.Providers

AspNet.Security.OpenId.Providers is a collection of security middleware that you can use in your ASP.NET Core application to support OpenID 2.0 authentication providers like Steam or Wargaming. It is directly inspired by Jerrie Pelser's initiative, Owin.Security.Providers.

The latest official release can be found on NuGet and the nightly builds on MyGet.

Build status

Getting started

Adding external authentication to your application is a breeze and just requires a few lines in your Startup class:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options => { /* Authentication options */ })
            .AddSteam()
            .AddOpenId("StackExchange", "StackExchange", options =>
            {
                options.Authority = new Uri("https://openid.stackexchange.com/");
                options.CallbackPath = "/signin-stackexchange";
            });
}

public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
}

See the /samples directory for a complete sample using ASP.NET Core MVC and supporting multiple external providers.

Contributing

AspNet.Security.OpenId.Providers is actively maintained by:

We would love it if you could help contributing to this repository.

Security policy

Please see SECURITY.md for information about reporting security issues and bugs.

Support

Need help or wanna share your thoughts? Don't hesitate to join us on Gitter or ask your question on StackOverflow:

License

This project is licensed under the Apache License. This means that you can use, modify and distribute it freely. See https://www.apache.org/licenses/LICENSE-2.0.html for more details.

Providers

Links to the latest stable and nightly NuGet packages for each provider, as well as a link to their integration documentation are listed in the table below.

If a provider you're looking for does not exist, consider making a PR to add one.

Provider Stable Nightly Documentation
OpenId NuGet MyGet N/A
Steam NuGet MyGet Documentation

aspnet.security.openid.providers's People

Contributors

aspnet-contrib-service-account[bot] avatar dependabot[bot] avatar hallipr avatar joskraps avatar kevinchalet avatar kinosang avatar martincostello avatar pranavkm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnet.security.openid.providers's Issues

OnAuthenticated event not firing - Can't set Identity

There is an issue when setting Identity.
image
A breakpoint in the OnAuthenticated method is never hit, so I really can't set the Identity.
Authentication happens just fine, and CallbackPath is showed right after, as supposed.
I noticed you @kelvinmac has the same issue. Don't know if your breakpoints are hit though.
Any suggestions?
Or just any suggestion for getting Steam ID?
I'm kinda stuck because I can't retrieve any user data.

Thanks.

ASP.NET Identity

I have a similar problem as #25. I created a new project .NET Core > ASP.NET Core Web Application (.NET Core) > Web Application (Change Authentication > Individual User Accounts), I added this nuget package and added a line to Startup.cs:

            app.UseIdentity();

            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
            app.UseSteamAuthentication();

            app.UseMvc(
                routes => { routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });
        }

But I get just one claim from steam and that is

http://schemas.microsoft.com/ws/2008/06/identity/claims/authenticationmethod: Steam

No webpage was found for the web address: http://127.0.0.1:50000/signin-steam

Describe the bug

No webpage was found for the web address: http://127.0.0.1:50000/signin-steam
services.AddAuthentication().AddSteam(options =>
            {
                options.ApplicationKey = "xx";
                options.SaveTokens = true;
                
                options.Events.OnTicketReceived = context_ =>
                {
                    var steamUserAsClaims = context_.Principal;
                    var identityUser = context_.HttpContext.User;

                    return Task.CompletedTask;

                };
                options.Events.OnAuthenticated = context_ =>
                {
                    var steamUserAsClaims = context_.Identity;
                    var nameIdentifier = steamUserAsClaims.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
                    var name = steamUserAsClaims.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;

                    // NOPE: Identity user not initialized yet in context_.HttpContext.User

                    context_.HttpContext.User.Claims.Append(new Claim(ClaimTypes.NameIdentifier, nameIdentifier));
                    context_.HttpContext.User.Claims.Append(new Claim(ClaimTypes.Name, name));

                    return Task.CompletedTask;
                };

            });

Expected behaviour
Working callback path

Actual behaviour
404, i dont know how to create callback path which alllows me to manage data from Steam.

Steam OpenID & JWTs

When using the default JWT middleware instead of cookies I get An unhandled exception occurred while processing the request. The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler' which cannot be used for SignInAsync.

From ConfigureServices:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateAudience = true,
            ValidateIssuer = true,
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ValidAudience = Configuration["Jwt:Issuer"],
            ValidIssuer = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new 
            SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
         };
     })
     .AddSteam(options =>
     {
         options.CallbackPath = "/verify";
     });

Is there any way to override the /verify callback, manually call the library to authenticate the user, then issue a JWT afterwards? My understanding is SignInAsync is being called automatically.

TL;DR: Can I override the verification callback and incorporate it into my own logic, e.g. verify the user and return a value?

Thanks,
Jacob

Blazor Wasm + Web API -> how to return Steam details to Blazor WASM

Provider name

Hi, I'm working on Blazor Wasm + Web API. In Blazor Wasm, the user can click the button to authenticate their SteamId to use the website.

How it works

This is how it works at the moment:

  1. User clicks the button to use their SteamId to use the website
  2. I call my Web API to access the Steam website, the user authenticates.
  3. The Web API has the Steam details.
  4. The question is how should I return this data to Blazor Wasm?

My Web API Startup class, ConfigureServices:

            //services.AddAuthentication...
            .AddSteam(x =>
            {
                //x.CallbackPath = $"Blazor Wasm?";
                //x.AccessDeniedPath = "some url";
                x.ApplicationKey = "key";
                //x.Events.OnAuthenticated = OnAuthenticated;
            });

I don't know how to handle this. As far as I know, Blazor Wasm doesn't support creating controllers (It if were, I would have just called endpoint in Blazor Wasm from my Web API). The idea is to authenticate users with their SteamIds to use certain features of the Blazor app.
I understand that this is not an issue in your library but I would appreciate any help to solve this issue. Thank you for any help.

Additional information

I'm using AspNet.Security.OpenId.Steam 5.0.0 and Net 5.0.

Steam sign in works after second try

Describe the bug
When I try to sign in to my website through Steam, each time I have to repeat twice to make it actually sign in me in. Looks like on the gif below and is very similar to issue #79 but I applied the solution from it tho still having this problem.
Also I'm not having this issue when I run the website locally.

Code
Startup

services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; })
                .AddCookie(options =>
                {
                    options.Cookie.SameSite = SameSiteMode.Unspecified;
                    options.LoginPath = "/signin";
                    options.LogoutPath = "/signout";
                    options.AccessDeniedPath = "/";
                    options.Events.OnValidatePrincipal = ValidationHelper.Validate;
                    options.ExpireTimeSpan = TimeSpan.FromHours(12);
                }).AddSteam(x => x.ApplicationKey = Configuration["SteamAPIKey"]);

...
// CheckSameSite method I copied from https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/
services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
                options.OnAppendCookie = cookieContext =>
                    CookiesHelper.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                    CookiesHelper.CheckSameSite(cookieContext.Context, cookieContext.CookieOptions); 

            });

System Information
Website is hosted on Ubuntu 18.04 on nginx webserver, user is Windows 10 using Firefox

The website is live at: https://www.unturnedstrike.com/

I actually doubt it's an issue with library, but my set up. Could you help me solve it anyways?
Thanks

How to use options pattern in service registration?

I try like this:

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(IdentityConstants.ApplicationScheme, options =>
            {
                options.LoginPath = "/account/signIn";
                options.LogoutPath = "/account/signOut";
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/Authentication/SignIn";
                options.LogoutPath = "/Authentication/SignOut";
            }).AddOpenId();

services.AddOptions<OpenIdAuthenticationOptions>().Configure<IServiceScopeFactory>((options, sp) =>
            {
//Do somthing
}

I've got this error:"ArgumentException: The authority or an absolute metadata endpoint address must be provided. (Parameter 'options')"
what is wrong?
thank you.

Exception: sub claim is missing

Core 2.0
IdentityServer4: 2.02
AspNet.Security.OpenId.Providers.Steam: 2.0.0-rc2-0208

Getting this when trying to login with Steam:

                .AddSteam("steam", options =>
                {
                    options.ApplicationKey = "xxx";
                });
System.InvalidOperationException: sub claim is missing
   at IdentityServer4.Hosting.IdentityServerAuthenticationService.AssertRequiredClaims(ClaimsPrincipal principal)
   at IdentityServer4.Hosting.IdentityServerAuthenticationService.AugmentPrincipal(ClaimsPrincipal principal)
   at IdentityServer4.Hosting.IdentityServerAuthenticationService.<SignInAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.<HandleRequestAsync>d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer4.Hosting.FederatedSignOut.AuthenticationRequestHandlerWrapper.<HandleRequestAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at IdentityServer4.Hosting.BaseUrlMiddleware.<Invoke>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.<Invoke>d__7.MoveNext()

Inability to send custom extensions when issuing a challenge.

Describe the bug
We are unable to send custom extension values when a challenge is issued. We send the client id which is supplied when the user submits the login form via a query parameter.Dotnetopenauth was able to convert to our custom extension and send to the provider.

Steps To reproduce

  • Add openId configuration to startup, specifying the custom extension: options.Attributes.Add("openid.ns.alias1", "http://customExtensionDomain/ext/openid/client_id/1.0");
  • In the controller, add the parameter to authentication properties object: ap.SetParameter("alias1.client_id", loginModel.ClientId);
  • Inspecting the request, the client id is not sent as expected. Additionally, adding the attribute int he configuration adds an extra openid.ax prefix to the customer extension being added.

Expected behaviour
I would expect to be able to add the client id that was sent to the challenge request via adding it to the authentication properties object.

Actual behaviour
The openId provider does not look at the properties.Parameters dictionary when a challenge has been issued and does not add any values to the request.

System information:

  • OS:Windows 10
  • Library Version 3.1.1
  • .NET version 3.1

Steam Login Button

Would it be possible to change the output of the Steam Login Button to be an image?

Steam valid authentication returns to /signin-steam with parameters, and throws "Error 500" Without any information in Console.

Describe the bug
Sometimes (not always!!) after correct login by steam, when returning to signin-steam Error 500 is throwed.

Steps To reproduce
Just login by steam, with parameters:

<form method='post' action='/signin' name='steamAuth'>
                <input type='hidden' name='Provider' value='Steam'>
                <input type='hidden' name='ReturnUrl' value='"http://127.0.0.1/"'>

Expected behaviour
Correct login, and claim claims.

System information:

  • OS: Windows 10, and Ubuntu (2 different builds)
  • Library Version: latest
  • .NET Core 3.0

CallbackPaths not defined

Describe the bug
Sample project Mvc.Client does not work because the callback paths are not defined (e.g. "/signin-stackexchange")

Steps To reproduce
Run Mvc.Client and click Connect using StackExchange, enter credentials.

Expected behaviour
The sample should "work". It should contain a sample implementation for the callback routes.

Actual behaviour
After logging in to OpenId provider I am returned to http://localhost:54540/signin-stackexchange which results in HTTP ERROR 500. (Actually I am surprised that it is not a 404)

System information:

  • OS: Windows 10
  • Library Version: 5.0.0
  • .NET version: 5.0.201

OAuth with Steam and user data

Describe the bug
email is used for fields UserName and NormalizedUserName in AspNetUsers table.

Steps To reproduce
Regsiter to sample with steam account

Expected behaviour
Use the Steam username and not his email because you can't modify username by IdentityUI

Actual behaviour
Because a picture is better than a long speech:
image

System information:

  • OS: Windows 10
  • Library Version 3.0.0
  • .NET version 3.0

Additional context
My application is a Blazor server app.

Can you make Steam OpenID provider documentation ?

Blazor Server app doesn't find/execute the login endpoint when tested outside of Visual Studio

Hi, I've deployed a Blazor Server + Blazor Wasm apps to Heroku. Blazor Wasm calls one of the endpoints to login using Steam from Blazor Server. For some weird reason, this works when testing locally, however, when I pushed the app to Heroku it stops working (the page goes to /api/users/login endpoint and displays 404, not found). When I tested it locally, I pressed the button to authenticate using Steam, the page correctly reloaded and went to the Steam page to authenticate. It doesn't happen in the live version. When the page is on api/users/login (live version) I can hard reload the page and when that's done, it correctly goes to the Steam page to authenticate the user. I don't know why it works differently when it's live.

This is my Startup.ConfigureServices:

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(o =>
            {
                o.Cookie.Name = "session";
                o.LoginPath = "/api/users/login";
                o.LogoutPath = "/api/users/logout";
                o.AccessDeniedPath = "/";
                o.ExpireTimeSpan = TimeSpan.FromDays(30);
                o.Events.OnSignedIn += CookieDealer.OnSignedIn;
                o.Events.OnValidatePrincipal += CookieDealer.OnValidatePrincipal;

                o.Events.OnRedirectToLogin = context =>
                {
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };

                o.Events.OnRedirectToAccessDenied = context =>
                {
                    context.Response.StatusCode = 401;
                    return Task.CompletedTask;
                };
            })
            .AddJwtBearer(options =>
            {
                //stuff
            })
            .AddSteam(x => x.ApplicationKey = "key");

This is my Startup.Configure:

            //Was needed to avoid C# anti-forgery exception
            app.UseCookiePolicy(new CookiePolicyOptions()
            {
                MinimumSameSitePolicy = SameSiteMode.Lax
            });

            //Just for debugging it live
            app.UseDeveloperExceptionPage();
            app.UseWebAssemblyDebugging();
            if (env.IsDevelopment())
            {
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (var description in provider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"{description.GroupName}/swagger.json", $"v{description.GroupName.ToUpperInvariant()}");
                }
            });

            app.UseRouting();
            app.UseCors("MyCorsPolicy");

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseClientRateLimiting();
            app.UseIPFiltering();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });

Example of calling the endpoint from Blazor Wasm:

                <a href="/api/users/login" style="margin-top: 8px">
                    <img src="icons/steam.png" alt="Sign in through Steam" />
                </a>

This is my login endpoint:

        [HttpGet("login")]
        public IActionResult Get()
        {
            if (User.Identity?.IsAuthenticated ?? false)
            {
                return Redirect("/");
            }

            return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "Steam");
        }

Expected behavior

I expect the page to correctly load the Steam page to authenticate the user when the app is deployed.

Additional information

I'm not sure what's wrong with my code here. It works when it's local but as soon as I deploy it on Heroku, it displays 404 when clicked on the button. In the local testing, it immediately went to the Steam page to authenticate.
I'm sorry that it's not a direct issue with your library but I would really appreciate some help since I've spent on this issue like 6 hours already. Thank you for help.

Update 1:
Chrome Console says:
Displaying NotFound because path 'api/users/login' with base URI 'url' does not match any component route

Update 2:
It seems that maybe CORB may be the issue here?
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://steamcommunity.com/openid/... with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

But I don't know what could cause it?

Update 3:
It seems like the Blazor Server doesn't need to be live for it to not work. I just tested it outside of Visual Studio (by running .exe file on my PC, both in debug and release) and it doesn't work, it displays 404, not found. So it looks like that it only works when I test it inside Visual Studio.

Update 4:
I've noticed that when I debug it in Visual Studio, Chrome console states:

blazor.webassembly.js:1 dbug: Microsoft.AspNetCore.Components.Routing.Router[3]
      Navigating to non-component URI 'https://localhost:6001/api/users/login' in response to path 'api/users/login' with base URI 'https://localhost:6001/'

When I test it outside of Visual Studio:

dbug: Microsoft.AspNetCore.Components.Routing.Router[1]
      Displaying NotFound because path 'api/users/login' with base URI 'https://localhost:5001/' does not match any component route

Why does it behave differently when I test it inside Visual Studio and outside?

Update 5:
I've created a new project - Blazor Wasm ASP.Net Core hosted (the original one wasn't that) just to test Steam authentication. When I published the app, the first call to Steam was successful. However, any further calls were unsuccessful (404, not found were shown). I have no idea why is this happening.

ASP.NET 5 Support

Support for ASP.NET 5 will be available for the currently shipping OpenID providers soon after the final .NET 5.0 release ships in November 2020.

In the meantime, packages for ASP.NET 5 RC1 are available from our MyGet feed starting with version 5.0.0-rc.1.20466.50.

Steam Auth Connection With React?

Describe the bug
I saw something about steam&jwt are not safe together. But I wanna do a react app with a asp.net core backend but I dont know how can i authorize myself in react to access my api without jwt using cookies.

Getting Steam User Data

I made a demo .net core framework application using this and intigrated it with the code provided in the sample in this repo. I got as far as bringing up the steam page for loggining in, but when the login in a success and the site redirects the user, I have no way to view the user data. The sample code uses @if (User?.Identity?.IsAuthenticated ?? false), but when I try that the code always goes to the else block.

Github Repo: https://github.com/bkonzUNOmaha/SteamOpenIDTest/tree/master/Steamtest2/src/Steamtest2

Anti-forgery Token Invalid Solution - Chrome 84

In newer versions of Chrome when authenticating with Steam, the correlation cookie is not sent back.

The correlation cookie must be set to Secure for SameSite:Lax for it to be returned.

This can be achieved by the adding the following in Startup.cs:

.AddSteam(options =>
                    {
+                      options.CorrelationCookie.SameSite = SameSiteMode.None;
+                      options.CorrelationCookie.SecurePolicy = CookieSecurePolicy.Always;
                    }

Is there any possibly to set Secure to Always by default?

ASP.NET Core 3.0.0 release

I've merged #53 to dev and created a new rel/3.0.0 branch for it.

However I'm on vacation for the next two weeks so, unless it waits until after then, I won't be able to help out with pushing the final 3.0.0 release to NuGet.org.

/cc @PinpointTownes @poke

Identity not being set on successful login

I have been having an issue where the users identity is not being set on successful login. Subsequent requests are being authorized, but i need to redirect the user to a register page if they have not yet registered. This action is decorated with the authorize and ValidateAntiForgeryTokenattributes.

If i remove the authorize but leave the ValidateAntiForgeryToken, the next request gets 400 - because when the token was generated for an anonymous user and when the user posts, they are posting with their identiy cookie and is therefore not the same user that generated the token.-. I also don't want to do hacky fix because i would like the user to be redirect to their previous page with or without authorize attribute.

I did notice an odd log right after authenticating, i'm not sure what it means but google indicates that it can't find an action.

I'm running under asp.net core 2.1 (with the latest SDK v2.1.401)

Management >       Executed action Vme.Store.Controllers.AuthenticationController.ChallengeClient (Management ) in 1196.7113ms
Management > info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
Management >       Request finished in 1248.9989ms 302 
Management > info: Microsoft.AspNetCore.Server.Kestrel[32]
Management >       Connection id "0HLGDMTFA4BO3", Request id "0HLGDMTFA4BO3:00000003": the application completed without reading the entire request body.
Management > info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
Management >       Request starting HTTP/1.1 GET http://localhost:44395/signin-steam?state=CfDJ8CgsnUyyvudFnNksvaJN-OL1LKRBIcgnvPG-xlYPgy5y4....
            services.AddAuthentication(options =>
                {
                    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultSignOutScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    options.DefaultForbidScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(options =>
                {
                    options.LoginPath = "/Authentication/SignIn";
                    options.LogoutPath = "/Authentication/SignOut";
                    options.Cookie.Expiration = TimeSpan.FromHours(1);
                    options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
                    options.SlidingExpiration = true;
                    options.Cookie.Name = "Vme.Store.WebAuth";
                    options.Cookie.HttpOnly = true;
                })
                .AddSteam(options =>
                {
                    options.ApplicationKey = config.ApiKey;
                    options.Events.OnAuthenticated = OnClientAuthenticated;
                });
        private async Task OnClientAuthenticated(OpenIdAuthenticatedContext context)
        {
            var userManager = context.HttpContext.RequestServices.GetService<VmeUsermanager>();
             // Get the last segment which is the steam steamid
            var steamId = new Uri(context.Identifier).Segments.Last();

            if (!await userManager.IsRegisteredAsync(steamId))
                context.Ticket.Properties.RedirectUri = $"/Authentication/Register?hint=AuthMsg_RegisterRequired";

            // ** I have tried this an it still doesn't work ** //
            var identity = new ClaimsPrincipal(context.Identity);
            context.Request.HttpContext.User = identity;
        }
public class AuthenticationController : Controller
{
        // GET: Authentication/SignIn
        [HttpGet]
        [AllowAnonymous]
        public IActionResult SignIn()
        {
            return View();
        }

        //POST: Authentication/ChallengeClient
        [HttpPost]
        public IActionResult ChallengeClient()
        {
            return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "Steam");
        }

        [HttpGet]
        public async Task<IActionResult> Register(.. model)
        {
            return View(); // generates the Anti Forgery Token
        }

        //POST: Authentication/Register
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Register(.. model)
        {

        }
}

Question: Force Request.Schema under Docker or Azure Web App (Linux)

Hi,

I'm having an issue when I deploy an app to Azure Web App (Linux). These apps run under a Docker container. To the app, the request arrives with "http" schema. This causes a problem because when open id regenerates the redirect URL, it uses "http" instead of "https".

Do you know of a way to tell the app to use a different schema? Not the one in Request? Or to force Request.Schema to be "https"?

Alternatively (but very unlikely), is there a chance that you offer a setting to set the full URL for the call back (instead of just the path)?

Thanks

Login Uri with ReturnUrl parameter?

Provider name

Steam Authentic.

Expected behavior

I have a route called Privacy which has
[Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
value.
Whenever i want to access it without authorization it returns me to this url:
localwebsiteadress/authentication/login?ReturnUrl=%2FHome%2FPrivacy
This is login action in authentication controller:
`
[Route("Login")]
public IActionResult Login()
{
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "Steam");
}

    [Route("Login")]
    [HttpPost]
    public IActionResult Login(string ReturnUrl)
    {
        return Challenge(new AuthenticationProperties { RedirectUri = ReturnUrl }, "Steam");
    }`

And finally my startup.cs configuration:
`
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})

       .AddCookie(options =>
       {
           options.LoginPath = "/authentication/login";
           options.LogoutPath = "/authentication/logout";
           options.ReturnUrlParameter = "ReturnUrl";
       }).AddSteam(options =>
       {
           options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
           options.ApplicationKey = "secret";
       });

     `

Without any ReturnUrl parameters , just clicking login works very well and redirects me to steam login page but when i try to access privacy this error appears:

This localhost page can’t be foundNo webpage was found for the web address: https://localhost:44322/authentication/login?ReturnUrl=%2FHome%2FPrivacy

Additional information

Don't set auth cookie on failed sign-in

This issue can be tagged as a question.

Following my issues with failed userinfo requests (from #46), I decided to add a handler for OnTicketReceived and make the userinfo request myself. In this handler, I make the userinfo request with multiple API keys and authenticate the user when one of them succeed. I would also like to handle the case where none of the API keys work (however unlikely it may be) by not authenticating the user at all. I tried using context.Fail("some reason"), but this still seems to set the auth cookie on the client machine.

Do you know any way to completely fail the authentication process? Could you also tell me what the Success and Fail methods on TicketReceivedContext do?

ASP.NET Core 6 Support

Support for ASP.NET Core 6 will be available for the currently shipping OpenID providers soon after the final .NET 6.0 release ships in November 2021.

In the meantime, packages for ASP.NET Core 6 are available from our MyGet feed starting with version 6.0.0-preview.4.21312.40 for .NET 6 preview 4.

Return Steam Session ID

For calling certan services in Steam API I need the steamcommunity session ID. (g_SessionID on their site) is this posible and how is it posible with this module, can it be made posible?

Newtonsoft Json assembly manifest mismatch?

Using Providers version 3.1.0, and DotNet Core 3.1

I'm developing an Electron.Net application to pair with a website. I've already implemented OpenID and Steam login with no issues on the Asp.Net Core website, but I'm running into issues on the Electron client. I started by copying the the implementation for the website (which is rather straightforward). The one difference was I had to turn NodeIntegration off.

After logging into Steam, upon redirect an error pops up. Newtonsoft.Json is automatically installed to Version 10.0.3 via Nuget. I've also tried other version, but none seemed to work. I actually thought Newtonsoft was replaced by System.Text.Json with the latest version.

Output:

      Error from RemoteAuthentication: Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The located assembly's manifest definition does not match the assembly reference. (0x80131040).
stdout: fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
 ---> System.IO.FileLoadException: Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The located assembly's manifest definition does not match the assembly reference. (0x80131040)
File name: 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
   at AspNet.Security.OpenId.OpenIdAuthenticatedContext..ctor(HttpContext context, AuthenticationScheme scheme, OpenIdAuthenticationOptions options, AuthenticationTicket ticket)
   at AspNet.Security.OpenId.Steam.SteamAuthenticationHandler.<>c__DisplayClass1_0.<<CreateTicketAsync>g__RunAuthenticatedEventAsync|0>d.MoveNext() in /_/src/AspNet.Security.OpenId.Steam/SteamAuthenticationHandler.cs:line 119
--- End of stack trace from previous location where exception was thrown ---
   at AspNet.Security.OpenId.Steam.SteamAuthenticationHandler.CreateTicketAsync(ClaimsIdentity identity, AuthenticationProperties properties, String identifier, IReadOnlyDictionary`2 attributes) in /_/src/AspNet.Security.OpenId.Steam/SteamAuthenticationHandler.cs:line 56
   at AspNet.Security.OpenId.OpenIdAuthenticationHandler`1.HandleRemoteAuthenticateAsync() in /_/src/AspNet.Security.OpenId/OpenIdAuthenticationHandler.cs:line 211
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   --- End of inner exception stack trace ---
   at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

Has steam has changes the return data?

AspNet.Security.OpenId.Steam.SteamAuthenticationHandler[0]
The userinfo request was skipped because an invalid identifier was received: https://steamcommunity.com/openid/id/.

It was http://steamcommu... before.

I think the problem lies here.

if (!identifier.StartsWith(SteamAuthenticationConstants.Namespaces.Identifier, StringComparison.Ordinal))

Users are signed out when website is restarted

Steam authentication,
.net core 2
asp.net core 2

The users stay authenticated as long as the site is not restarted. When the website is restarted, the users have to sign in again.

The sample project exhibits the same behavior

Return Steam SessionID

For calling certan services in Steam API I need the steamcommunity session ID. (g_SessionID on their site) is this posible and how is it posible with this module, can it be made posible?

Ability to use multiple API keys

The user information endpoint seems to have been rate limited recently, but it returns a 403 Forbidden, not 429 Too Many Requests. Could the option to cycle multiple API keys be added?

I can submit a PR if it'll fast track the process.

Add Steam provider

Because the asp.net team has implemented their UseOpenIdConnectAuthentication() middleware to use only OAuth2 and OpenID Connect (based on OAuth2) which means it is not compatible with providers like STEAM that use OpenID 2.0.

There seems to be some other interest in this as well. REF: http://stackoverflow.com/questions/31101803/implementing-openid-in-asp5

I believe this makes more sense to support in a community project like this instead of main repo. REF: https://github.com/aspnet/Security/

OpenId.Steam fails to load user data

I have added the service like
.AddSteam(options => { options.UserInformationEndpoint = SteamAuthenticationDefaults.UserInformationEndpoint; options.ApplicationKey = "*Correct Key*"; });
It works correctly and creates a valid cookie, however when trying to load the data from the steam api I receive the following error
warn: AspNet.Security.OpenId.Steam.SteamAuthenticationHandler[0] The userinfo request was skipped because an invalid identifier was received: https://steamcommunity.com/openid/id/76561198832475883.

After sign in by Steam App (for not logged in Steam Users) tries to redirect to 127.0.0.1:50000 (again)

Hi, i have to re-open issue.

Now i have Kestrel Server, fully configured with your tips. Problem is (propably) that im using Nginx reverse proxy, and it begins again:

image

My configuration:
Startup:

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";


        private void CheckSameSite(HttpContext httpContext, CookieOptions options)
        {
            if (options.SameSite == SameSiteMode.None)
            {
                var userAgent = httpContext.Request.Headers["User-Agent"].ToString();

                options.SameSite = (SameSiteMode)(-1);

            }
        }

        public void ConfigureServices(IServiceCollection services)
        {

            //services.AddGrpc();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            })
            .AddCookie(options =>
            {
                options.LoginPath = "/login";
                options.LogoutPath = "/signout";
            })

            .AddOpenId("Orange", "Orange", options =>
            {
                options.Authority = new Uri("https://openid.orange.fr/");
                options.CallbackPath = "/signin-orange";
            })

            .AddOpenId("StackExchange", "StackExchange", options =>
            {
                options.Authority = new Uri("https://openid.stackexchange.com/");
                options.CallbackPath = "/signin-stackexchange";
            })

            .AddOpenId("Intuit", "Intuit", options =>
            {
                options.CallbackPath = "/signin-intuit";
                options.Configuration = new OpenIdAuthenticationConfiguration
                {
                    AuthenticationEndpoint = "https://openid.intuit.com/OpenId/Provider"
                };
            })

            .AddSteam();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            services.AddLogging();

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("*")
                    .AllowAnyHeader()
                    .AllowAnyOrigin()
                    .AllowAnyMethod();
                });
            });

            services.Configure<CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = (SameSiteMode)(-1);
                options.OnAppendCookie = cookieContext =>
                    CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                    CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });


        }
        public void Configure(IApplicationBuilder app, ILoggerFactory logger)
        {

            logger.CreateLogger("Logging");



            app.UseStaticFiles();
            app.UseRouting();
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();

            });
            app.Use((context, next) =>
            {
                context.Response.Headers.Add("Access-control-allow-headers", "Content-Type, Accept, X-Requested-With, method");
                context.Response.Headers.Add("Access-control-allow-methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
                context.Response.Headers.Add("Access-control-allow-origin", "*");
                context.Response.Headers.Add("Access-control-allow-credentials", "true");
                return next.Invoke();
            });
            app.UseCors(option => option.WithHeaders("accept", "content-type", "origin"));
            app.UseCookiePolicy();
            app.UseCors(MyAllowSpecificOrigins);
            app.UseHsts();
            app.UseHttpsRedirection();
        }


    }

Program.cs

var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls($"{env_config.KestrelURL}")
                .UseStartup<Startup>()
                .ConfigureLogging(l =>
               {
                   l.ClearProviders();
                   l.AddConsole();
               })
                .Build();

If user is Logged into steam redirection after taking SteamId works fine, but if user has to provide password, or confirm "Continue as xxxx" app redirecting him to 127.0.0.1:50000.

NGinx listening to 50000 on localhost, and proxing it to subdomain "secure.example.com".

Originally posted by @kamilk91 in #71 (comment)

Update NuGet package

The current update with support for the updates for ASP.NET Core 2.0 is not live on NuGet. Could this be published?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.