How get user name in MVC WebAPI Controller - asp.net

I have a Logon Controller Get method where I want to return the user id.
I am using basic authorization and all work fine but in the Get method I am not able to get the correct user id.
This is the code :
public class LogonController : ApiController
{
[BasicAuthorize]
public string Get()
{
int id = WebSecurity.CurrentUserId; // returns -1
return id.ToString();
}
}
My application is based on MVC 4 internet template with authentication mode="Forms"
I am not sure how to configure the two authentication modes even they seem to be working.
Any suggestion ?
Thanks

Related

Need advice of where to put custom user authorization in ASP.NET Core

I need advice of where to put custom user authorization code in ASP.NET Core. I am somewhat a ASP.NET Framework developer and normally I will add code to Global.asax as a session_onstart event to look up a SQL table where users profile are stored that is used to determine what they can view in the rest of the application. With Global.asax this is only cause once per user session, so what I would like to do is the same kind of approach in ASP.NET Core which I am kind of new to but need advice where that check should be done
I would like to do is the same kind of approach in ASP.NET Core which
I am kind of new to but need advice where that check should be done
Well, based on your description, in asp.net core you can achieve that in many ways. For instances, you could set in following places:
program.cs/startup.cs files
Using Middleware file
Using Action Filter
Let's, consider below example using action filter
Role and permissison:
First we are defining the role and the permission.
public enum Role
{
User,
Admin,
SuperAdmin
}
public enum Permission
{
Read,
Create,
Update,
Delete
}
Authorization On Action Filter:
public class AuthorizeActionFilter : IAuthorizationFilter
{
private readonly Role _role;
private readonly Permission _permission;
public AuthorizeActionFilter(Role item, Permission action)
{
_role = item;
_permission = action;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var isAuthorized = context.HttpContext.User.Claims.Any(c => c.Type == _role.ToString() && c.Value == _permission.ToString());
if (!isAuthorized)
{
context.Result = new ForbidResult();
}
}
}
Note: Check your user claim from the HttpContext if that containts either Admin or Read authorization.
Controller:
[Authorize(Role.User, Permission.Read)]
public IActionResult MemberList()
{
var memberList = _context.Members.ToList();
return View(memberList);
}
Output:
You even can implement that using Middleware. Asp.net 6 now providing couple of other mechanism now a days, you could have a look below official implementations as well.
Role-based authorization
Claims-based authorization
Policy-based authorization
Custom Action Filter

How to hide Controllers routes in ASP.NET WebApi

I have a WebApi project and I got myself in this situation. Let's say that I have a Route :
[Authorize]
[RoutePrefix("api/v1/GG")]
public class StorkUserController : ApiController
{
private IAuthenticationManager Authentication
{
get { return HttpContext.Current.GetOwinContext().Authentication; }
}
[Route("UpdateUser")]
[HttpPost]
So When I start the application, if i directly type in my browser this route :
http://localhost:52494/api/
I will get this Error with some details :
Or if I navigate to http://localhost:52494/api/v1/GG I get :
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:52494/api/v1/GG/'.","MessageDetail":"No type was found that matches the controller named 'v1'."}
How to prevent for this Happen since these routes could be easily to be found, and instead of it, show something like "ERROR 404"! Thanks!

How to Get CurrentUserId in WebApi2

Current User Id in WebApi2
I want to get to current user-id, I tried following things
string currentUserId = User.Identity.GetUserId()
string currentUserId1 =
System.Web.HttpContext.Current.User.Identity.GetUserId();
but it always returns null,
Another approach is :-
To implement extension method on IIdentity interface in Microsoft.AspNet.Identity.IdentityExtensions.
but don't know how to implement this method with interface IIdentity as input parameter.
Event having content on internet and stack-overflow none of the example worked
Not able to understand why the above one liner code doesn't work.
Can any body give working example. Stuck here.
Where in your code are you using this?
Not only, but you should be able to, get this atleast inside a Api controller.
using Microsoft.AspNet.Identity;
---
[Authorize]//makes sure the user is authenticated
//or use User.Identity.IsAuthenticated before getting the ID.
public class AccountController : ApiController
{
public IHttpActionResult Get()
{
string userId = User.Identity.GetUserId();
return Ok();
}
}

Page reachable if user connected or not.

I am currently working on a website with MVC5 and Identity.
I have a page which is reachable when a user is connected (with an account) but also when he is not. If he is connected I want to display some information .
If he is not connected I want to display less information and I want to invite him to log in.
I don't know how to implement such a page. I have this controller :
[Authorize]
public class PController : Controller
{
private int UserId;
public ActionResult Index(int userId ) {
UserId = Convert.ToInt32(((ClaimsIdentity) User.Identity).FindFirst("test").Value);
PModel model = new PModel(UserId);
return View(model);
}
}
and my model :
public class PModel {
public int UserId { get; set; }
public PModel(int userId) {
........
}
In both cases, I would like to call the Index method, and do the processings according to the connexion in the model :
public PModel(int userId) {
if(userConnected) {
} else {
}
}
I don't know whether it's possible like this.
You don't do this in your model (typically). If you want to use the default forms authentication model that comes with ASP.net, you need to set it up in your web.config and provide appropriate login/logout actions etc. In the config, you have something like this:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="30" name=".MySite" protection="All"/>
</authentication>
The Authorize attribute on your action will stop the code within that method from running if the user is not authenticated. The forms authentication code will redirect the user to the 'loginUrl' specified in your web.config if they come directly to a page in your site without logging in.
From your comment, I have misread your question. You will need to remove the Authorize attribute altogether then, and you can set your model userConnected property based on the Request.IsAuthenticated property in the controller.

Add token parameter to all urls inside an asp.net mvc 2 site

I've integrated some pages written in ASP.NET MVC 2, into a classic webform app.
Everything works well except the authentication system.
The authentication system is using some token added to the url like :
/Account/Profil/Details.aspx?AUTHID=2ddc098a-cf0b-fd81-afb7-d41f35010b9f
When i reach my asp.net mvc pages (all these pages must be secured), they must include that AUTHID parameter.
I'm using the core Webform control to secure the pages, and this control check for the AUTHID token in the url. So basicly my route must include the
?AUTHID=2ddc098a-cf0b-fd81-afb7-d41f35010b9f
What the best and clever way to do this ?
I don't want to pass the AUTHID parameter manually in all controller actions.
Thanks for your help.
You can solve your problem by extending the ASP.NET routing mechanism. Just create a custom route and override the GetVirtualPath function.
public class TokenizedRoute : Route
{
public TokenizedRoute(string url, IRouteHandler routeHandler) : base(url, routeHandler)
{
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
string tokenValue = "your token value";
values.Add("AUTHID", tokenValue);
return base.GetVirtualPath(requestContext, values);
}
}
See my blog post for more details.
You could use a jQuery solution to append a token to the query string of all links:
$("a").each(function (index, link)
{
$(link).attr("href", $(link).attr("href") + "?AUTHID=" + token);
});
But I agree with dknaack, I would say you should reconsider your authentication logic if at all possible.
You can save the AuthId in the Session object and create a custom Authorize Attribute.
Attribute
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
// your custom logic depending on Session["AuthId"]
return httpContext.Session["AuthId"] != null;
}
}
Controller
public class MyController : Controller
{
[CustomAuthorize]
public ActionResult MyActionMethod()
{
return View();
}
}
hope this helps

Resources