How to block access to controller via changing Url in ASP.NET Core? - asp.net-core

I want to access page when user clicks to button.
By changing url, such as ..../Member/Batch/Create I want my site redirect user to another page.
How can I do this via ASP.NET Core MVC 3.1?

Use:
Create Batch
See this answer and help for more details.

Do you mean we could only access the controller by using button?
If this is your requirement, you could try to check the Request.Headers["Referer"].ToString() to make sure just which url could access this controller.
Like below:
public IActionResult Privacy()
{
var re = Request.Headers["Referer"].ToString();
if (Request.Headers["Referer"].ToString() != "https://localhost:44342/home/index")
{
return View("Error");
}
else
{
return View();
}
}
Result:

Related

Override routing in ASP.NET CORE 2.2 to implicitly route to an area if user have some permissions

I'm looking for an easy way to change routing behaviour a little and add extra area data into route data if the user has some sorts of permissions.
Let's say for regular user url site/shop/12 should route to ShopController
but for admin it should route to AdminArea/ShopController
Please, consider that this question isn't about HTTP redirect, it's about extending infrastructure on a framework level to allow extra functionality on Routing or controller invocation
You could use URL Rewriting Middleware to redirect the request for Admin user
1.Create a Redirect rule:
public class RewriteRules
{
public static void RedirectRequests(RewriteContext context)
{
//Your logic
var IsAdminRole = context.HttpContext.User.IsInRole("Admin");
if (IsAdminRole)
{
var request = context.HttpContext.Request;
string area = "AdminArea";
var path = request.Path.Value;
//Add your conditions of redirecting
if(path.Split("/")[1] != area)// If the url does not start with "/AdminArea"
{
context.HttpContext.Response.Redirect($"/{area}{ request.Path.Value }");
}
}
}
}
2.Use the middleware in Startup Configure method:
app.UseAuthentication();//before the Rewriter middleware
app.UseRewriter(new RewriteOptions()
.Add(RewriteRules.RedirectRequests)
);
Add logic to the controller method that handles site/shop/12 to check if the user is an admin, and if it is, redirect to to the proper admin area and controller.
var isAdmin = IsUserAnAdmin();
if (isAdmin) {
// This will redirect to the Index method defined in the ShopController
// in the area name AdminArea
return RedirectToAction("Index", "Shop", new { Area = "AdminArea" });
}
I think the best way is to set the correct URLs on the front-end and then validate the request on the end-point doing something like this:
[HttpGet]
[Route("v1.0/download/document")]
public IActionResult download_document(int id, string token)
{
try
{
if (token == null || isNotAdmin(token))
return Unauthorized();
That way your end-points are protected and you avoid redirections. Plus, in my opinion everything makes a lot more sense on the front-end

How to redirect to action in ASP.NET Core WebAPI?

I've got two actions in my ASP.NET Core Web API application's controller:
[HttpGet("get-all")]
public IActionResult GetAll() { ... }
and
[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
...
return RedirectToAction("GetAll");
}
Delete action always redirects to itself and never to GetAll. Why so? In the same time similar redirect from Post action works ok.
Can't find any docs on the subject. Any help?
Have you tried to use RedirectToActionResult? Like this (change ControllerName with your actual Controller's name ):
RedirectToActionResult("GetAll", "ControllerName", null);
Documentation
Hope you'll find this useful.

Checking if the user is logged in asp.net mvc

In my application I am restricting some view and the user has to be logged in to view them. One way would be to check on every action if the user is logged in or not. But after a bit of research I found that asp.net MVS supports some global filter rules.
How do we use them? Ideally I would want to call a filter onBeforeAction and check if the user is logged in or not..
Is this a right approach? If yes, then can any body give me an example?
The easiest way is to add the Authorize attribute to your controller or action methods. For example:
public class MyController : Controller
{
//Normal action
public ActionResult DoSomethingForAnyone() { }
//Secured action
[Authorize]
public ActionResult DoSomethingOnlyForAuthorisedUsers() { }
}
Alternatively you can secure the entire controller and exclude actions you want to be accessible to anonymous users:
[Authorize]
public class SecureController : Controller
{
public ActionResult DoSomething() { }
[AllowAnonymous]
public ActionResult DoSomethingForAnyone() { }
}
Your [Authorize] will not work with the custom login. If you are using Form Authentication or other Authentication method than [Authorize] will work smoothly.
For custom login on success set
FormsAuthentication.SetAuthCookie([user name], false);
This will make your [Authorize] attribute to work properly.
And for logout use below statement
FormsAuthentication.SignOut();
If you follow the above solution than it will reduce your code as well as valid user check on before Action call.

Ember + web api single page redirect

I have a asp.net mvc web api app with ember and simplemembershipprovider. I am using the ember template and with it, ember app is created upon user successfully logged in in the home controller.
public ActionResult Index(string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return View("App");
}
ViewBag.ReturnUrl = returnUrl;
return View();
}
Sometimes user would click a link in an email with an id when visiting the site, if the url includes an id, upon successful login, I want to redirect user to a detail page base on the provided id in the url. An example would be http://siteURL.com/#/product/1412 . I am having a hard time figuring out how to do this. Since this is a client side ember route, MVC does not differentiate between this route and http://siteURL.com so it just ignores the redirect request. Here is what I have tried.
assign the url in the login controller - nothing happens after json data is returned, stays in the login page and never hit the HomeController even though user is not authenticated.
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
returnUrl = "http://siteURL.com/#/product/1412";
return Json(new { success = true, redirect = returnUrl });
use response redirect. Same as #1
Response.Redirect(returnUrl);
Assigned url in home controller, same as above.
if (User.Identity.IsAuthenticated)
{
returnUrl = "http://siteURL.com/#/product/1412";
return View("App");
}
ViewBag.ReturnUrl = returnUrl;
return View();
Most browsers don't even send the # up to the server, so you won't have it to redirect. Here's a few options
Don't use the hash, not every browser supports it, http://emberjs.com/guides/routing/specifying-the-location-api/
Give them a fake address that redirects, http://siteURL.com/Redirect/product/1412
inject that url into some js on the page that redirects on load

user isn't authenticated in custom authorize attribute

I've made my own authorize attribute, and this is what it looks like
public class RedirectAuthorize : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "NotExist" }));
}
}
}
So if the user isn't authenticated, I want them to get redirected to the NotExist controller. I've debugged and it seems that unauthorized users get in the if clause, which is correct. But I've also tried doing this with logged in users, and they get in the if clause as well which is wrong.
I dont understand why this is happening. It makes me hesitate about whether my log-in didnt work. Is this the right way of logging a user in?
FormsAuthentication.SetAuthCookie(acc.username, false);
I've never made a log-in system in asp.net mvc before, so please tell me what I'm doing wrong.
Edit:
It seems that the default [Authorized] attribute isn't working either... I really think the problem lays in the log in:
[HttpPost]
public ActionResult Login(User acc)
{
if(ModelState.IsValid)
{
if (Validate(acc.username, acc.password))
{
FormsAuthentication.SetAuthCookie(acc.username, false);
return RedirectToAction("Index", "System");
}
}
ModelState.AddModelError("IncorrectDetails", "Wrong details. Please try again.");
return View(acc);
}
The custom authorize attribute looks correct.
Since you are setting the cookie yourself I would guess you are not using the built-in membership provider.
If you set the cookie yourself, you also need to read the auth cookie and set the Identity and Principal objects on each request. Otherwise, HttpContext.User.Identity.IsAuthenticated will always be false, which seems to be what you are experiencing.