-Authorize- not working with 2 ASP.NET MVC controllers - c#

I'm building an ASP.NET MVC web app with 2 controller, 1 that send requests to an API and the other one that will handle authentication. The app build just fine but the authorize tag is not working, I can easily access the secret page without having the cookie.
This is the Access controller:
public class AccessController : Controller
{
public IActionResult Index()
{
return View();
}
public IActionResult Login()
{
return RedirectToAction("Index");
}
[Authorize]
public IActionResult Secret()
{
return View();
}
}
And this is the startup.cs file:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//services.AddControllers();
// Add session
services.AddDistributedMemoryCache();
services.AddSession();
// Add services to the container.
services.AddSingleton<IClient, ClientConcessionario>();
services.AddAuthentication("CookieAuth").AddCookie("CookieAuth", config =>
{
config.Cookie.Name = "CookieAuth";
config.LoginPath = "/Access/Login";
});
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSession();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapDefaultControllerRoute();
});
;
}
}
I can views all the urls of both the controllers, but I shouldn't be able to access the secret page without a cookie. Any clue?

You should call UseAuthentication() and UseAuthorization() in Configure method BEFORE UseRouting.

Related

Asp.Net Core API shuts down automatically when authorize is used

I have created an Asp.Net Web API for google authentication and here is my code in satrtup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = GoogleDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddGoogle(options =>
{
options.ClientId = "591241482908-66qgk38nbf1un6xxxxxxxxx.apps.googleusercontent.com";
options.ClientSecret = "GOCSPX-xxxxxxxxxxxxx";
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
And there is Login Controller
[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
[HttpGet("{id}")]
[Authorize]
public ActionResult<string> Get(int id)
{
return Ok(this.User);
}
}
Now the code builds successfully, but whenever I run the web API the console and the application shuts down automatically. How Can I solve this?

AllowAnonymous doesn't work as expected in Web API

In an ASP.NET CORE 3.1 Server-Side Blazor app, I am not able to get the AllowAnonymous working for a post type of request web API. The get requests do not have any issues.
Along with the solution for it work, please advise me about the needed security. Perhaps I lowered the security in my trials to get the post request work.
These 3 logs appear for every post request:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
....
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddDefaultUI()
.AddEntityFrameworkStores<EpisodeContext>();
services.AddMvc(options=> {
options.RespectBrowserAcceptHeader = true; })
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddRazorPages();
services.AddServerSideBlazor().AddCircuitOptions(option => { option.DetailedErrors = true; });
services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
services.AddHttpContextAccessor();
services.AddAuthorization(config =>
{
config.FallbackPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.AddPolicy("RequireAdministratorRole",
policy => policy.RequireRole("admin"));
});
...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
API Controller:
[AllowAnonymous]
[Route("api/[controller]")]
[ApiController]
[Produces("application/json")]
public class DailyContentController : ControllerBase
{
[HttpPost("likeepisode"), AllowAnonymous]
public async Task<bool> LikeEpisode(string episodenumber)
{
bool result = await _CDService.LikeEpisode(episodenumber);
return result;
}
}
Plesk Hosting Settings:
Web Application Firewall
I have been able to stop the unintended redirect by setting the preferred domain to none in the hosting settings:

Cors implementation in .Net Core 3.1 project with Oracle Database Host

Only one HOST can connect to the API, in this case it is an Oracle server.
I added Cors as per Microsoft docs, still other HOST can connect to my API. Has anyone tried to add an Oracle Database HOST? Is there something wrong with the configuration?
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddHttpClient();
services.AddCors(options =>
{
options.AddPolicy(name: "CorsPolicy",
builder =>
{
builder.WithOrigins("http://oraas1111.net:1001")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors("CorsPolicy");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireCors("CorsPolicy");
});
}
Controller.cs
[EnableCors("CorsPolicy")]
[Route("[controller]")]
[ApiController]
public class Controller : ControllerBase
{
[HttpPost]
[Route("/Service/[action]")]
public async Task<ActionResult<Request>> Update(Request data)
{
}
[HttpGet]
[Route("/GET_Service/[action]")]
public ActionResult Test()
{
return Ok();
}
}
You have to move services.AddCors() to the top, before AddControllers()

issue with post(create a record) webapi in blazor server app

I create a blazor server app project and I am using built in webapi framework
I am checking a create record webapi in postman but it give a 204 content means my webapi run but it return 204 content see below image
//webapi test in postman but it return 204 content
blazor server app
EmpsController.cs
namespace CrudBlazorServerApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EmpsController : ControllerBase
{
private readonly sqldbcontext _context;
public EmpsController(sqldbcontext context)
{
_context = context;
}
// GET: api/Emps
[HttpGet]
public async Task<ActionResult<IEnumerable<Emp>>> Getemps()
{
return await _context.emps.ToListAsync();
}
// GET: api/Emps/5
[HttpGet("{id}")]
public async Task<ActionResult<Emp>> GetEmp(int id)
{
var emp = await _context.emps.FindAsync(id);
if (emp == null)
{
return NotFound();
}
return emp;
}
[HttpPost]
public async Task<ActionResult<Emp>> PostEmp(Emp emp) //here I am facing issue record is not created
{
_context.emps.Add(emp);
await _context.SaveChangesAsync();
return CreatedAtAction("GetEmp", new { id = emp.empid }, emp);
}
Startup.cs
namespace CrudBlazorServerApp
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers()
.AddJsonOptions(options => options.JsonSerializerOptions.IgnoreNullValues = true);
services.AddDbContext<sqldbcontext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconnn")));
services.AddRazorPages();
services.AddServerSideBlazor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<sqldbcontext>();
context.Database.EnsureCreated();
}
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseCors(policy =>
policy.WithOrigins("https://localhost:44399") // client address
.AllowAnyMethod()
.WithHeaders(HeaderNames.ContentType));
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
}
}
why it give 204 no content?
.net core project version : netcoreapp3.1
what I am trying:
I comment this line
await _context.SaveChangesAsync();
but record not created
please help
which place need to correction?

Action routing in .Net Core 3 Web API

I am busy migrating an existing-working WebApi from .Net Core 2.2 to 3, however, the routing stopped working. I keep getting a 404 Not Found message.
Would like to use the action names as part of the route template in my controller, for example:
[Route("/api/[controller]/[action]")]
Call example: /api/Lookup/GetBranchesAsync
I'm just really confused about why it stopped working.
Please see the code below.
Startup:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<ILookupService, LookupService>();
services.AddScoped<IFranchiseRepo, FranchiseRepo>();
services.AddScoped<ILogRepo, LogRepo>();
services.AddSingleton<IConfiguration>(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Controller:
[ApiController]
[Route("/api/[controller]/[action]")]
[Produces("application/json")]
public class LookupController : Controller
{
private readonly ILookupService lookupService;
public LookupController(ILookupService lookupService)
{
this.lookupService = lookupService;
}
[HttpGet]
public async Task<IActionResult> GetBranchesAsync()
{
}
[HttpGet("{branchID}")]
public async Task<IActionResult> GetBranchSEAsync(int? branchID)
{
}
}
Any advice on what the issue could be?
According to https://github.com/aspnet/AspNetCore/issues/8998, in .NET Core 3.0 Async is skipped by default in Action name. Your endpoint is available at /api/Lookup/GetBranches. You can change this behaviour by replacing
services.AddControllers();
with
services.AddControllers(options => options.SuppressAsyncSuffixInActionNames = false);
in ConfigureServices method, or just use the new routes

Categories

Resources