禁用Asp.Net Core 3.0中的身份验证以进行开发

时间:2019-11-25 14:49:29

标签: c# asp.net-core .net-core asp.net-core-3.0

在开发过程中如何为具有[Authorize]属性的控制器禁用身份验证? Here是.net core 2的答案,但它使用的AddMvc()在.net core 3.0中未使用。

我尝试过:

    services.AddControllers().AddMvcOptions(opts => opts.Filters.Add<AllowAnonymousFilter>());

它仍然返回401;我不知道那是不是在正确的轨道上。

3 个答案:

答案 0 :(得分:1)

只需转到项目中的launchSettings.json:

1

然后将“ anonymousAuthentication”设置为“ true”。

答案 1 :(得分:0)

在开发过程中如何使用“测试”声明信息自动登录用户。例如,假设您在非开发环境中时,可以使用如下所示的方式来授权用户:

// Checked the database and user is legit so populate the claims
// Create the identity for the user. userList is var or list populated from database. userEmail is the user's email or some other identifier.
identity = new ClaimsIdentity(new[] {
    new Claim(ClaimTypes.Name, userList.fullname),
    new Claim(ClaimTypes.Role, userList.userrole),
    new Claim(ClaimTypes.NameIdentifier, userEmail),
}, CookieAuthenticationDefaults.AuthenticationScheme);

var principal = new ClaimsPrincipal(identity);
var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
return RedirectToAction("Index", "Home");

在开发中,您可以执行以下操作:

// You may need to inject Microsoft.AspNetCore.Hosting.IHostingEnvironment. I use .Net core 2.2 so not sure about 3.
if (env.EnvironmentName == "Development")
{
    // In Development so create "test" claim information and automatically authorize the user
    // Create the identity for the user
    identity = new ClaimsIdentity(new[] {
    new Claim(ClaimTypes.Name, "Test User"),
    new Claim(ClaimTypes.Role, "Tester"),
    new Claim(ClaimTypes.NameIdentifier, "tester@test.com"),
    }, CookieAuthenticationDefaults.AuthenticationScheme);

    // Populate the session user name
    HttpContext.Session.SetString(SessionUserName, userList.fullname);

    var principal = new ClaimsPrincipal(identity);
    var login = HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);
    return RedirectToAction("Index", "Home");
}

答案 2 :(得分:0)

您可以尝试这样的事情。

public class Startup 
{
   public Startup(IConfiguration configuration, IWebHostEnvironment env)
   {
            Configuration = configuration;
            Environment = env;
   }

   public Microsoft.AspNetCore.Hosting.IWebHostEnvironment Environment { get; }

   public void ConfigureServices(IServiceCollection services)
   {
            services.AddControllers(opts =>
            {
                if (Environment.IsDevelopment())
                {
                    opts.Filters.Add<AllowAnonymousFilter>();
                }
                else
                {
                  var authenticatedUserPolicy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
                  opts.Filters.Add(new AuthorizeFilter(authenticatedUserPolicy)); 
                 }
            });
    }

}