Hello stack overflow peeps,
Having a bit of an issue implementing an oAuth system.
//https://github.com/justintv/Twitch-API/blob/master/authentication.md
public ActionResult AuthorizeTwitch(CancellationToken cancellationToken) {
var twitchBridge = new TwitchBridge();
var codes = Request.Params.GetValues("code");
var token = Request.Params.GetValues("access_token");
// stage 1 Initial Handshake
if (codes == null && token == null) {
return Redirect(twitchBridge.AuthorizeUrl());
}
// stage 2 We have a code so we are at stage two request the token
else if (codes != null) {
return Redirect(twitchBridge.RetrieveToken(codes[0]));
}
// SAVE OAUTH STUFF DOWN HERE.
// THEN REDIRECT
return RedirectToAction("Index", "Home");
}
The above action seems to work however when for stages 1 and 2 but when I get a response form stage 2 I get redirected to a URL that looks like.
http://localhost:58434/Home/AuthorizeTwitch#access_token=anaccesstoken&scope=user_read
This hits my action but I cant access the value for access_token. I can access Request.Url.OriginalString but the return string looks like.
http://localhost:58434/Home/AuthorizeTwitch
Debugging and looking into the request object and the URL object nothing seems to have stored anything from the # onwards. I suspect this has something to do with the routes setup for my site.
The relevant route that is being hit is
routes.MapRoute(
name: "Default2",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Can any one see what i'm doing wrong?
In case it is something to do with my actually request to twitch this is how im building the url.
public string AuthorizeUrl() {
return string.Format(
"{0}{1}?response_type=code&client_id={2}&redirect_uri={3}&scope={4}",
TwitchUrlBase,
TwitchAuthorizeMethod,
ClientId,
HttpUtility.UrlEncode(TwitchAuthorizeRedirectURL),
TwitchAuthorizeScope
);
}
public string RetrieveToken(string code) {
return string.Format(
"{0}{1}?response_type=token&client_id={2}&client_secret={3}grant_type=authorization_code&redirect_uri={4}&scope={5}",
TwitchUrlBase,
TwitchAuthorizeMethod,
ClientId,
ClientSecret,
HttpUtility.UrlEncode(TwitchAuthorizeRedirectURL),
TwitchAuthorizeScope
);
}
The fragment is not supposed to be sent by the client to the server, so it makes sense that it's not there. Did you mean to send a query?
Related
My route is correctly configured as I already saw it in another questions.
Web API uses MapHttpRoute, and it uses System.Web.Http. I decorated my Actions with [System.Web.Http.HttpPost] but it seems not to work and it returns the error message:
The requested resource does not support http method 'GET'
I tried this solution [System.Web.Http.AcceptVerbs("GET", "POST")] as I see here on the same question. The requested resource does not support HTTP method 'GET' and it worked.
But on the API Help Page, this is what I see
the METHOD of the Action is GET that that should be POST.
Maybe I am missing something that should not or should be implemented on the Action I am working with.
Here is my code in the Controller.
[HttpPost, Route("DestroySession/{userID}", Name = "DestroySession"), AcceptVerbs("GET" , "POST")]
public async Task<IHttpActionResult> DestroyUserSession(string userID)
{
SystemResult systemResult = new SystemResult();
await Task.Run(() => {
IAbstractLogic<UserInput, SystemResult> systemProcess = new LogoutLogic();
UserInput userInput = new UserInput
{
UserID = userID
};
systemResult = systemProcess.doProcess(userInput);
}).ConfigureAwait(false);
return Content(HttpStatusCode.OK, new
{
message = systemResult.ResultMessage, status = systemResult.ResultCode == 0
});
}
And here is my WebApiConfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Any help would be much appreciated. Regards
Whooosh! It seems that my code is working very fine. I just tested it in POSTMAN and it literally works. All I can say is that if your request is to POST something. you need a third party application to test it out. Testing it on the browser alone gives you so much problem.
I have a login controller with a post action which redirects to home page after successful login. I am using following code for redirection, which works well in Chrome and Firefox. but doesn't redirect in IE and EDGE, and response cookie not set
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToRoute("default", new { controller = "", action = "" });
}
}
My Login action
public IActionResult Login(string userName, string password)
{
try
{
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password))
throw new InvalidOperationException("Username/Password can not be empty");
var session = CreateSession(userName, password);
var returnUrl = Request.Query["returnUrl"];
return RedirectToLocal(returnUrl);
}
catch (Exception ex)
{
ModelState.AddModelError("Login", ex.Message);
}
return View();
}
I am using my own session management for which I set session cookies like following
CookieOptions option = new CookieOptions();
option.Path = AppPath;
option.Domain = AppHost;
httpContextAccessor.HttpContext.Response.Cookies.Append(AppSessionToken, "SomeSessionId", option);
After searching a lot for exact answer, I found that Internet Explorer (all versions) doesn't allow you to specify a domain of localhost, a local IP address or machine name. When you do, Internet Explorer simply ignores the cookie.
So I removed following line
option.Domain = AppHost;
from my codes and everything start working as expected on both IE and EDGE.
Since you didn't post your route mapping from Startup.cs, I am not sure why it didn't work for you. Maybe you shouldn't override the controller and action parameter by passing new { controller = "", action = "" } into the RedirectToRoute() method?
Instead, have you tried just calling the method with the route name, like
return RedirectToRoute("default");
Or, you can use RedirectToAction()
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
// action, controller and route values
return RedirectToAction("index", "home", new { area = "" });
In an existing C# Web project here at my Job I've added a Web API part.
In four of my own classes that I use for the Web API I need to access some of the existing Controller-classes. Right now I just create a new Instance of them and everything works as intented: ProductController controller = new ProductController();
Still, creating a new ProductController while one should already exist obviously isn't a good practice. I know the Controllers are created in the Config-file in the Routes.MapHttpRoute, since it's using the C# Web MVC method. Below I've copied that piece of code:
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "MyProject.Controllers" }
);
route.DataTokens["UseNamespaceFallback"] = false;
I've tried to access these Controllers in my one of my API-classes like so:
private void getControllerInstance()
{
var url = "~/Products";
// Original path is stored and will be rewritten in the end
var httpContext = new HttpContextWrapper(HttpContext.Current);
string originalPath = httpContext.Request.Path;
try
{
// Fake a request to the supplied URL into the routing system
httpContext.RewritePath(url);
RouteData urlRouteData = RouteTable.Routes.GetRouteData(httpContext);
// If the route data was not found (e.g url leads to another site) then authorization is denied.
// If you want to have a navigation to a different site, don't use AuthorizationMenu
if (urlRouteData != null)
{
string controllerName = urlRouteData.Values["controller"].ToString();
// Get an instance of the controller that would handle this route
var requestContext = new RequestContext(httpContext, urlRouteData);
var controllerFactory = ControllerBuilder.Current.GetControllerFactory();
// TODO: Fix error (The controller for path '/Products' was not found or does not implement IController.) on this line:
var controllerbase = (ControllerBase)controllerFactory.CreateController(requestContext, controllerName);
controller = (ProductController)controllerbase;
}
}
finally
{
// Reset our request path.
httpContext.RewritePath(originalPath);
}
}
As you might have noticed by the TODO-comment, at the line var controllerbase = (ControllerBase)controllerFactory.CreateController(requestContext, controllerName);, I get the following error:
HttpException was unhandler by user code: The controller for path '/Products' was not found or does not implement IController.
Does anyone know how to fix this error? Has this got something to do with one of the following two lines of the code in the Config-file?
namespaces: new[] { "MyProject.Controllers" }
route.DataTokens["UseNamespaceFallback"] = false;
Or did I do something else wrong?
A tip to everyone: Don't continue programming when you are very, very tired.. Anyway, everything was correct except for a small flaw:
My API Controller is called ProductsController and my normal (default) controller is called ProductController. In the method above I use:
var url = "~/Products";
To access the ProductController..
So, after removing the "s" (and for good measure make everything lower case) I have the following instead:
var url = "~/product";
And now it works..
I have a method in the controller ApplicationsController, in which I need to get the base URL for an action method:
public ActionResult MyAction(string id)
{
var url = Url.Action("MyAction", "Applications");
...
}
The problem is that this includes the string id from the current route data, when I need the URL without (the URL is used to fetch content from a CMS on a URL-based lookup).
I have tried passing null and new { } as the routeValues parameter to no avail.
The matching route is as follows (above all other routes):
routes.MapLowercaseRoute(
name: "Applications",
url: "applications/{action}/{id}",
defaults: new { controller = "Applications",
action = "Index", id = UrlParameter.Optional });
I've seen a couple of other questions touch on this but none of them seem to have a viable solution. At present, I am resorting to hardcoding the path in the controller; however, I'd like to be able to abstract this into an action filter, so I need to be able to generate the URL.
Is there a clean/conventional way to prevent this behaviour?
Ok, I see the problem. It's something called "Segment variable reuse". When generating the routes for outbound URLs, and trying to find values for each of the segment variables in a route’s URL pattern, the routing system will look at the values from the current request. This is a behavior that confuses many programmers and can lead to a lengthy debugging session. The routing system is keen to make a match against a route, to the extent that it will reuse segment variable values from the incoming URL. So I think you have to override the value like Julien suggested :
var url = Url.Action("MyAction", "Applications", new { id = "" })
Ended up getting around this with a different approach. The only way I could come up with to prevent arbitrarily-named route values from being inserted into the generated URL was to temporarily remove them from RouteData when calling Url.Action. I've written a couple of extension methods to facilitate this:
public static string NonContextualAction(this UrlHelper helper, string action)
{
return helper.NonContextualAction(action,
helper.RequestContext.RouteData.Values["controller"].ToString());
}
public static string NonContextualAction(this UrlHelper helper, string action,
string controller)
{
var routeValues = helper.RequestContext.RouteData.Values;
var routeValueKeys = routeValues.Keys.Where(o => o != "controller"
&& o != "action").ToList();
// Temporarily remove routevalues
var oldRouteValues = new Dictionary<string, object>();
foreach (var key in routeValueKeys)
{
oldRouteValues[key] = routeValues[key];
routeValues.Remove(key);
}
// Generate URL
string url = helper.Action(routeValues["Action"].ToString(),
routeValues["Controller"].ToString());
// Reinsert routevalues
foreach (var kvp in oldRouteValues)
{
routeValues.Add(kvp.Key, kvp.Value);
}
return url;
}
This allows me to do this in an action filter where I won't necessarily know what the parameter names for the action are (and therefore can't just pass an anonymous object as in the other answers).
Still very much interested to know if someone has a more elegant solution, however.
Use a null or empty value for id to prevent Url.Action from using the current one:
var url = Url.Action("MyAction", "Applications", new { id = "" })
I was not entirely comfortable with the altering, transient or otherwise, of the RouterData in #AntP's otherwise fine solution. Since my code for creating the links was already centralized, I borrowed #Tomasz Jaskuλa and #AntP to augment the ExpandoObject, I was already using.
IDictionary<string,object> p = new ExpandoObject();
// Add the values I want in the route
foreach (var (key, value) in linkAttribute.ParamMap)
{
var v = GetPropertyValue(origin, value);
p.Add(key, v);
}
// Ideas borrowed from https://stackoverflow.com/questions/20349681/urlhelper-action-includes-undesired-additional-parameters
// Null out values that I don't want, but are already in the RouteData
foreach (var key in _urlHelper.ActionContext.RouteData.Values.Keys)
{
if (p.ContainsKey(key))
continue;
p.Add(key, null);
}
var href = _urlHelper.Action("Get", linkAttribute.HRefControllerName, p);
In my Asp.Net Mvc project I'd like to have a good looking urls, e.g. mysite.com/Page2, and I want to redirect from my old style urls (such as mysite.com?page=2) with 301 state so that there won't be two urls with identical content. Is there a way to do it?
As far as I know Asp.Net binding framework doesn't make difference between query string and curly brace params
I am not sure, I got your question right. It seems, your current setup relies on those GET parameters (like mysite.com?page=2). If you dont want to change this, you will have to use those parameters further. There would be no problem in doing so, though. Your users do not have to use or see them. In order to publish 'new style URLs' only, you may setup a URL redirect in your web server. That would change new style URLs to old style URLs.
The problem is the 301. If the user requests an old style URL, it would be accepted by the webserver as well. Refusing the request with a 301 error seems hard to achieve for me.
In order to get around this, I guess you will have to change your parameter scheme. You site may still rely on GET parameters - but they get a new name. Lets say, your comments are delivered propery for the following (internal) URL in the old scheme:
/Article/1022/Ms-Sharepoint-Setup-Manual?newpage=2
Note the new parameter name. In your root page (or master page, if you are using those), you may handle the redirect permanent (301) manually. Therefore, incoming 'old style requests' are distinguishable by using old parameter names. This could be used to manually assemble the 301 in the response in ASP code.
Personally, I would sugesst, to give up the 301 idea and just use URL redirection.
Well, as far as I can see performing such redirection in ASP.NET MVC might be tricky. This is how I did it:
global.asax:
routes.Add(new QueryStringRoute());
routes.MapRoute(null, "Article/{id}/{name}",
new { controller = "Article", action = "View", page = 1 },
new { page = #"\d+" }
);
routes.MapRoute(null, "Article/{id}/{name}/Page{page}",
new { controller = "Article", action = "View" },
new { page = #"\d+" }
);
QueryStringRoute.cs:
public class QueryStringRoute : RouteBase
{
private static string[] queryStringUrls = new string[]
{
#"~/Article/\d{1,6}/.*?page=\d{1,3}"
};
public override RouteData GetRouteData(HttpContextBase httpContext)
{
string url = httpContext.Request.AppRelativeCurrentExecutionFilePath;
foreach (string queryStringUrl in queryStringUrls)
{
Regex regex = new Regex(queryStringUrl);
if (regex.IsMatch(url))
{
long id = 0; /* Parse the value from regex match */
int page = 0; /* Parse the value from regex match */
string name = ""; /* Parse the value from regex match */
RouteData rd = new RouteData(this, new MvcRouteHandler());
rd.Values.Add("controller", "QueryStringUrl");
rd.Values.Add("action", "Redirect");
rd.Values.Add("id", id);
rd.Values.Add("page", page);
rd.Values.Add("name", name);
rd.Values.Add("controllerToRedirect", "Article");
rd.Values.Add("actionToRedirect", "View");
return rd;
}
}
return null;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
QueryStringUrlController.cs:
public class QueryStringUrlController : Controller
{
public RedirectToRouteResult Redirect(long id, int page, string name,
string controllerToRedirect, string actionToRedirect)
{
return RedirectToActionPermanent(actionToRedirect, controllerToRedirect, new { id = id, page = page, name = name });
}
}
Assuming you have such routing as in my global.asax file (listed above) you can create a custom Route class that will handle incoming requests and map them on a special redirection controller which will then redirect them to appropriate urls with 301 state. Then you must add this route to global.asax before your "Article" routes
If you're using IIS 7, the URL Rewrite Module should work for your scenario.