I have an Intranet application with Windows authentication based on MVC4.
When I need the WindowsIdentity for authorization purpose in a Controller I just use
HttpContext.User.Identity
Now I wanted to use the new Asp.Net WebAPI for some Ajax calls.
Is there a way to get the WindowsIdenty object in the same easy way as in an MVC Controller?
Please don't reference the HttpContext from a controller.
You can access the Controllers User property which is way of accessing the Identity through without a dirrect reference to HttpContext.
public class MyController : ApiController
{
public string Get()
{
var indenty = this.User.Identity;
}
}
Why
The controllers User property provides a level of abstraction which allows for easier mocking and thus unit testing. This abstraction also allows for greater portability e.g. if this was WebApi Self Host you wouldn't even have access to HttpContext.
To read more about how to unit test and mock the User property read here. For more information re: portability read here.
Related
I am using ASP.Net core and I have a requirement to access a specific HTTP Header in a business logic class (not a controller or action).
To provide a full picture of the configuration here, I have a custom ASP.Net Core Middleware which based on some logic will add a value into a custom HTTP Header, it is the value from this header that I need to access in the business logic class.
Currently the way that I achieve this is to inject an HttpContextAccessor, using the following DI registration.
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
In the class which requires access to the HTTP Headers I then request an IHttpContextAccessor using constructor injection and use this to access the relevant HTTP Header.
Doing the above works fine and gives me the results that I require, looking around various articles on the Internet however the general consensus appears to be to avoid using HttpContext.Current in ASP.Net Core.
If the above is the case, is there a better way for my business logic class to access the value that my custom middleware is inserting into a custom HTTP Header?
I should be clear, whilst at present the middleware is storing the required value in a HTTP Header for use by the business logic class, I am open to other methods of the middleware making the required value available to the business logic class if there is a better approach.
Any questions or clarifications, please let me know.
There is no HttpContext.Current in ASP.Net Core, so it's easy to avoid using it. You would have to implement your own extension method if you wanted it, but the general feeling in the .Net Core community is that it's much better to use IHttpContextAccessor.
In earlier versions of .Net Core an implementation of IHttpContextAccessor was auto registered in the DI container. In more current version you have to register it yourself with the line of code you mentioned:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Injecting IHttpContext into your method that needs access to the headers is a workable approach. Or if you like you could use a helper method that places a copy of the headers in a simpler structure and then pass that object in to your class since it doesn't really need access to the full HttpContext.
I'm moving a Web Api 2 project to MVC 6, since Microsoft is merging the two APIs in ASP.NET 5. In my WebApi project I had a custom Attribute Filter class that would authenticate, authorize and prevent transaction replays using a combination of public key, private key and HMAC authentication (basically, doing this with some tweaks to fit into my project).
Now in MVC6, as far as I understand I must stop using anything in the Microsoft.Web.Http namespace and instead use Microsoft.AspNet.Mvc. So I have done that, but the Microsoft.AspNet.Mvc.Filters doesn't seem to have any equivalent of Web Api 2's IAuthenticationFilter.
This is a problem for me because my customer AuthenticationFilter implemented all of IAuthenticationFilter, with all the logic in there. More importantly, it was using the Context to temporarily store the public key of the account, so my controller could access it to load up the account in turn.
So my question is, what is the proper way to filter requests in MVC6, using an Authentication Filter-like class to intercept the requests and return the appropriate status codes? I can't find any article that goes specifically in these details (they all tend to cover MVC5).
I know it's an older question, but hopefully someone (maybe even yourself) might find value in the answer.
MVC6 does in fact have an alternative. You have an
public abstract class AuthorizationFilterAttribute :
Attribute, IAsyncAuthorizationFilter, IAuthorizationFilter, IOrderedFilter
which basically tells you, that you can create your custom class, derive it from this (namespace of all of these interfaces, btw, is Microsoft.AspNet.Mvc.Filters and that should be it. You can either decorate the action with it, or you can do this in Startup.cs, to apply to all actions:
public void ConfigureServices(IServiceCollection services)
{
// Add MVC services to the services container.
services.AddMvc(options =>
{
// add an instance of the filter, like we used to do it
options.Filters.Add(new MySpecialFilter());
});
services.AddTransient<LogFilter>();
}
If you want to use a bit more logic in the filter (e.g. my LogFilter above) which is instantiated through DI, you need to use either Service Filters or Type Filters.
You can now decorate the actions with [ServiceFilter(typeof(LogFilter))] or use o.Filters.Add(new ServiceFilterAttribute(typeof(LogFilter))); in the Startup.cs file. But keep in mind, to do this you need to register the type with the DI container, like I did above with the .AddTransient<>() call.
IAuthenticationFilter is no more and IAuthorizationFilter simply does not replace it in MVC 6
Reason: authentication is NOT EQUAL to authorization.
Therefore IMO the authentication filter should stay available!
I've project using Entity Framework 5 Code First, WebApi, ASPNET MVC 4, Repository and Unit of Work pattern, etc.
My architecture is as follows:
One project for the POCOS
One project with the context, Repository, Unit Of Work, etc
One project with the contracts (IRepository, IUnitOfWork, etc)
One WebApi project which holds ApiControllers for each entity of the model (GET, POST, PUT, DELETE).
Now, if I don't want to use SPA (as I don't have time right now to learn it) and I want to do something quick, What should I do? a new ASPNET MVC 4 project with Controllers inheriting from Controller rather than ApiController, and those controllers consuming the WebApi controllers?
Like this?
public ActionResult Index()
{
return View(WebApiProj.Uow.Houses.GetAll());
}
That doesn't seems to be quite good as it should be creating a Get pointing to the WebApi controller in the other project.
I'm thinking about this architecture, because mobile clients, web clients and any other clients would be calling the same services which sounds good.
Any advices on this architecture? Pros or cons?
I am not sure if what you show is possible? WebApiProj.Uow.Houses.GetAll() Is treating Houses as if it was a class with a static GetAll function on it. Houses is an instance class that needs to be instantiated per request and may/should have constructor injection concerns to handle too... GetAll would normally be an instance method.
Given you are in a situation where you are going to have multiple code clients i.e. the WebApi controllers and the MVC controllers you should consider adding a Service Layer to your project. http://martinfowler.com/eaaCatalog/serviceLayer.html.
Your Service Layer will probably take the form of a single class (if this is a small ish project but split it up if needed), it will have the Repositories and the Infrastructure code injected. You should end up with a series of CRUD and UseCase sounding method names that contain the orchestration logic between repositories, factories and unit of work classes.
public interface IMyServiceLayerClass
{
IEnumerable<House> GetAllHouses();
House SaveHouse(House house);
IEnumerable<Windows> GetAllHouseWindows(int houseId);
//etc
}
public class MyServiceLayerClass : IMyServiceLayerClass
{
private readonly IRepository<House> _houseRepository;
private readonly IUnitOfWork _unitOfWork;
private readonly IRepositoryTypeB _repositoryTypeB;
Public MyServiceLayerClass(IUnitOfWork unitofwork, IRepository<House> houseRepository, IRepositoryTypeB repositoryTypeB)
{
//Populate the private readonly's
}
public IEnumerable<House> GetAllHouses()
{
return _houseRepository.GetAll();
}
Your two types of controller can then accept the Service class and have very thin logic just to forward on to the service layer.
public class HomeController : Controller
{
private readonly IMyServiceLayerClass _myServiceLayerClass;
public HomeController(IMyServiceLayerClass myServiceLayerClass)
{
_myServiceLayerClass= myServiceLayerClass;
}
public ViewResult Index()
{
return View(_myServiceLayerClass.GetAllHouses());
}
Same for the Api:
public class HouseController : ApiController
{
private readonly IMyServiceLayerClass _myServiceLayerClass;
public HouseController (IMyServiceLayerClass myServiceLayerClass)
{
_myServiceLayerClass= myServiceLayerClass;
}
public IEnumerable<House> Get()
{
return _myServiceLayerClass.GetAllHouses();
}
This will allow you to reuse the same business logic and orchestration across the controllers abstract the logic away from your WebApi and Mvc applications.
This code could easily live in your project that defines the contracts as it is only dependent upon interfaces. Or you could add its interface into contracts too and then create another project class Domain or Service which can hold the implementation of the service class.
I would strongly suggest you leave you Controllers to do what they do best and let them handle the delegation of the UI specific elements and re-factor non UI specific logic into a reusable service layer. This would allow Unit tests for controllers to focus on testing for the correct action result and status codes etc and allow your domain logic to be tested independently.
Take a look at my answer for another architecture question on MVC. The key for your question is to have an application or domain layer that both the MVC Controller and Web API Controllers can use to access the business model (The M in MVC). You do not want to call the Web API directly from the MVC Controller as it has overhead for serialization and de-serialization that is not required here. Instead call the application/domain layer directly.
I'm using custom asp.net membership provider with underlaying nhibernate data access code, which is fine. Now I need to exercise these methods using tests.
Anyone interested in suggesting how these methods should be tested? with providing some links explaining test methods using some standars maybe ?
This is my first question so be gentle :)
When it comes to unit testing any code that does something with the database or a 3rd party library you should de-couple these dependencies so that your tests only test your code.
For example, if we have a method in our membership provider for adding a single user, what we want to be testing is that our code for this single method works correctly and not that the database is up and running or that methods called by this method work. Our unit test should still pass even if the database is offline or if method calls on other classes fail.
This is where Mocking comes into play. You'll want to mock out your data context and set up any methods you'll be using on it so that you can control its response.
Look closely at the methods you have in your membership provider. What should each one do? That's the only thing you really want to test. Does this method, as a standalone unit, do the job I'm expecting it to.
Membership providers are pretty difficult to mock and test, so personally I don't bother. What I do however is place all my membership code in classes that are easily testable.
Most of my custom providers look something like this:
public class CustomMembershipProvider : MembershipProvider
{
private readonly IUserService _userService;
public ButlinsMembershipProvider()
{
_userService = DI.Resolve<IUserService>();
}
public override bool ValidateUser(string username, string password)
{
return _userService.Authenticate(username, password);
}
}
In this example, I would write integration tests to verify the behavior of the user service. I don't test the provider.
I have a wcf 4.0 service , I am running it locally in IIS express and am using azman to manage security. I am able to use the declarative syntax to secure the services, and prevent class instantiation in a class library. However when I decorate a method in the class it has no effect.
[PrincipalPermission(SecurityAction.Demand, Role = "AdminRole")] //THIS WORKS
public class MaintainUser
{
[PrincipalPermission(SecurityAction.Demand, Role = "CreateNewUserx")] //THIS DOES NOT WORK
public void CreateNewUser()
{
if (ViterraSecurity.VerifyAccess.HasOperation("CreateNewUserx", ViterraSecurity.VerifyAccess.BasisOperations.CreatUser))
{
return;
}
throw new AccessViolationException("CreateNewUser");
}
}
Is it possible to enable security checks on methods?
I'm guessing that CreateNewUserx is an operation or task in AzMan, not a role. AuthorizationStoreRoleProvider only recognizes AzMan roles, and PrincipalPermission only checks the roles exposed by an IPrincipal. However, this is a bit of a backwards way of using AzMan, since the main point of an operations-based authorization mechanism is to allow roles to be user-configurable and allow the application to only worry about operations.
I would recommend scrapping your demands for roles in favour of demanding only operation permissions. With such an approach, you would need to change either your permission (and attribute) or your principal implementation, or both to be aware of AzMan operations.