I have a folder with resources and I'd like to give opportunity to all users with right token get access it.Requests like:
www.mysite.com/uploads/images?token = some security value
So I need to handle all requests that starts with
www.mysite.com/uploads
chek for right token and approve or reject request.Could you give a basic example?
Why not just create a route for www.mysite.com/uploads/images/token?
routes.MapRoute(
"Uploads", // Route name
"uploads/images/{token}", // URL with parameters
new { controller = "uploads", action = "images", token = "" } // Parameter defaults
);
}
This route should be placed at top of your route list and would catch route that starts with /uploads... Your users would be routed to uploadsController (in this case) and would execute the images Action Method passing Token as a string parameter.
Related
for example I was on the home page, it has the route name "home", after I left on another page for example edit, how to get the name of the previous route on the edit page (here it is home)? thanks
you can get the referrer and try to "match" it with the routing service to see if a route exists for this path:
$referer = $request->headers->get('referer'); // get the referer, it can be empty!
if (!\is_string($referer) || !$referer) {
echo 'Referer is invalid or empty.';
return;
}
$refererPathInfo = Request::create($referer)->getPathInfo();
// try to match the path with the application routing
$routeInfos = $this->router->match($refererPathInfo);
// get the Symfony route name if it exists
$refererRoute = $routeInfos['_route'] ?? '';
Check out the full snippet on my blog.
I would like your opinion in order to achieve something. I have an api and I want to restrictionate the access of the user. But short story long, in action login controller of page /login I generate the token for the user autheticated and I return it. Well, here comes one of my question/problem. It's mandatory in a action controller to return a response, and my token it's send in json format and it's displayed on browser, but I don't want this, I just want to keep in response or in something so that my angular part to take that token and to take care of it in its way. So my method login:
public function loginAction(Request $request)
{
$username= $this->get('security.token_storage')->getToken()->getUser()->getEmail();
$serviceUser = $this->container->get('ubb_user_login');
$tokenUser = $serviceUser->generateToken($username);
$response = new JsonResponse(array('Token' => $tokenUser));
return $response;
}
2nd problem. I do not know in angular where to extract the token. In a controller I tried something:
app.controller('loginApi', function ($scope, $http, $window){
$http.get(
'/api/user/login'
).then(function (success) {
$scope.token = success.data.Token;
$window.localStorage.setItem('Token', token); // it's okay used like this localStorage?
});
});
Here, I want only to take the token from /login action, to save it in local storage, and then to display it on every request using $http request interceptor. That part works. If I send a random string in header auth it's working and it gives me access to api:
function httpInterceptor() {
return {
request: function(config) {
config.headers.authorization = 'jdjdnnkdkd';
return config;
},
responseError: function(errorResponse) {
switch (errorResponse.status) {
case 403:
window.location = '/login';
break;
case 401:
window.location = '/login';
}
return $q.reject(errorResponse);
}
}
}
So, the problems I encounter:
1) How to send the token in order for angular to take it, but to not be displayed in the browser? Let's say that I have a menu that access the api, and if the user it's not authenticated,clicking on a link unauthenticated it's sending me on the login page, and after I auth with success, to redirect me on the menu?
2) After returning the token, where exactly to use it in angular? In which controller? And how to save it?
Much appreciation, thank you.
It seems like you need a separate api resource for working with the tokens. Have you tried using FOSOAuthServeBundle? It helps a lot with setting up oauth authentication, tokens etc.
In general you need to have a separate call for the token, i.e.:
angluar app makes request to a get token resource, a token is returned and temporarily stored in the angular app
use that token for each subsequent request - check the oauth bundle config on how to set which urls have to be oauth protected, but that bundle takes care of this for you
Regarding your angular issue, look at this q/a How to store authentication bearer token in browser cookie using AngularJS
So, we're updating a project from web forms to .NET MVC. To support other applications that deep link into our application, I'm trying to add attribute routes to the relevant controller actions that mimic the old web forms paths.
I have an event action on the Home controller. The configuration has a route for this to remove the controller name.
routes.MapRoute(
name: "eventdetails_nohome",
url: "event/{id}/{occurrenceid}",
defaults: new { Controller = "Home", action = "Event", occurrenceid = UrlParameter.Optional },
constraints: new { id = #"\d+", occurrenceid = #"\d+" }
);
That route works just fine for routes like http://myapp/event/123/456, and the default routing like http://myapp/home/event?id=123&occurrenceid=456 also works.
So far so good, but if I add this route attribute to the action:
[Route("~/ViewEvent.aspx")]
public ActionResult Event(int id, int occurrenceid)
Then the only route that works is http://myapp/ViewEvent.aspx?id=91918&occurrenceid=165045. The routes that worked before start returning
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /event/123/456
I've used the routedebugger extension, and I can verify that even with the attribute route, my old route is still the first to work. So why would I be getting "resource cannot be found" errors?
Note: as a workaround, I've found that I can just do a traditional route configuration like
routes.MapRoute(
name: "Legacy event",
url: "ViewEvent.aspx",
defaults: new { Controller = "Home", action = "Event" }
);
I'm still curious why the attribute route would break existing routes, though, as I thought you were supposed to be able to use both at the same time.
Take a look at Attribute Routing in ASP.NET MVC 5
Another article with the same heading
Attribute Routing in ASP.NET MVC 5
Attribute routes overrides the convention based route. If you use more than one URL for action, you can use multiple route attributes on the action...
[Route("event/{id:int}/{occurrenceid:int}")]
[Route("event")]
[Route("~/ViewEvent.aspx")]
public ActionResult Event(int id = 0, int occurrenceid = 0) {
return View();
}
The following URLs all routed to the above action.
http://myapp/event/123/456
http://myapp/home/event?id=123&occurrenceid=456
http://myapp/ViewEvent.aspx?id=91918&occurrenceid=165045
We have files behind authentication, and I want to do different things for post-authentication redirect if the user entered the application using a URL of a file versus a URL of an HTML resource.
I have a URL: https://subdomain.domain.com/resource/45/identifiers/567/here/11abdf51e3d7-some%20file%20name.png/download. I want to get the route name for this URL.
app/console router:debug outputs this: _route_name GET ANY subdomain.domain.{tld} /resource/{id2}/identifiers/{id2}/here/{id3}/download.
Symfony has a Routing component (http://symfony.com/doc/current/book/routing.html), and I'm trying to call match() on an instance of Symfony\Bundle\FrameworkBundle\Routing\Router as provided by Symfony IOC. I have tried with with the domain and without the domain, but they both create a MethodNotAllowed exception because the route cannot be found. How can I match this URL to a route?
Maybe a bit late but as I was facing the same problem, what I come to is something like
$request = Request::create($targetPath, Request::METHOD_GET, [], [], [], $_SERVER);
try {
$matches = $router->matchRequest($request);
} catch (\Exception $e) {
// throw a 400
}
The key part is to use $_SERVER superglobal array in order to have all things setted straight away.
According to this, Symfony uses current request's HTTP method while matching. I guess your controller serves POST request, while your download links are GET.
The route name is available in the _route_name attribute of the Request object: $request->attributes->get('_route_name').
You can do something like this ton get the route name:
public/protected/private function getRefererRoute(Request $request = null)
{
if ($request == null)
$request = $this->getRequest();
//look for the referer route
$referer = $request->headers->get('referer');
$path = substr($referer, strpos($referer, $request->getBaseUrl()));
$path = str_replace($request->getBaseUrl(), '', $lastPath);
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($path);
$route = $parameters['_route'];
return $route;
}
EDIT:
I forgot to explain what I was doing. So basicly you are getting the page url ($referer) then taking out your website's base url with str_replace and then trying to match the remaining part of the path with a know route pattern using route matcher.
EDIT2:
Obviously you need to have this inside you controller if you want to be able to use $this->get(...)
I want to give the users a friendly URL, with the desired area, and whenever they enter it, the site is forwarded to the default controller/action., but I am having a real hard time figuring out how to do it.
Example: someone types http://mySite.com/System and the routing engine redirects to the complete default url http://mySite.com/System/Auth/SignIn
I tried this, but it isn't working
routes.MapRoute(
"System", // Route name
"System/{controller}/{action}", // URL with parameters
new { area = "System", controller = "Auth",
action = "SignIn", id = UrlParameter.Optional } // Parameter defaults
);
PS: as I am using areas, System in this case is the {area}, Auth is the {controller} and SignIn is the {action}.
Could use a SystemController at the root level of your application, of which the Index() action would simply redirect to /System/Auth/SignIn.
is there any Reverse Proxy Solution is the architecture which host your application ?