VS2013 (RTW): Authentication differences in SPA template vs MVC5 template? - visual-studio-2013

I've been playing with the new ASP.NET identity offerings in the VS2013 RTW MVC template (for "indivual user accounts"), and it works great: I am able to integrate Facebook login while customizing the way the data is serialized.
All well and good, but I noticed that if I create a new SPA app (instead of MVC), the authentication story seems very different. As an example:
From the SPA template:
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
From the MVC template:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
This is just the difference in constructors of the Account controller. There are many, many other differences as well. With the MVC version I was able to easily derive my own context class from ApplicationDBContext, and use that to store my own tables alongside the authentication tables. I couldn't figure out how to customize the data storage in the SPA template.
Also, the SPA template includes and uses this class:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
The MVC template doesn't define (or use) this class.
I don't understand why there needs to be any differences at all between an MVC template and an SPA template.
Could anyone give me some guidance as to why authentication is handled so differently in these two templates? Starting a project from scratch, is there a preferred path to follow between the two? (It seems like the code in the MVC template is best, especially in terms of customizing how the data is stored by defining a custom EF Context class.)
Thanks...
-Ben

Take MVC and SPA project templates as Controller vs ApiController implementation sample.
As well as CookieAuthentication and oAuthAuthentication.
MVC uses Controller at the first request as well as all subsequent requests (having request defined Action Methods).
SPA uses Controller at the first request to SPA and all other interactions are handled by ApiController.
MVC uses cookie authentication.
SPA uses oAuth authentication.
Now in real apps, we need to take mix of both. Stating this, you can use the IdentityModel.cs (ApplicationDBContext) and it's customized copy of MVC project in your SPA too.
In oAuth implementation, the token is issued in GrantResourceOwnerCredentials method of ApplicationOAuthProvider. The user verification uses the same database of Identity framework by default. Moreover, oAuth provide authentication check in ApiController. In the sample implementation, oAuth's ResourceOwner flow is provided where user's username and password are verified.
In my opinion, templates are starting point examples.

I did notice the same thing when I first looked at all the posts about changing the model for the user and I couldn't find the model in the SPA template. Of course, the difference as #jd4u pointed out is that one is based on Controller and the other on ApiController.
So, I decided to see what it would take to make the SPA solution use the same Identity Model extension as the MVC template. I created a post that goes through the process that I went through. There is a link at the bottom to download the code from GitHub.

Related

REST and spring-mvc

Since REST based controller methods only return objects ( not views ) to the client based on the request, how can I show view to my user ? Or maybe better question what is a good way to combine spring-mvc web app with REST, so my user always get the answer, not in just ( for example ) JSON format, but also with the view ?
So far as I understood, REST based controller would be perfectly fitting to the mobile app ( for example twitter ), where views are handled inside the app and the only thing server has to worry about is to pass the right object to the right request. But what about the web app ?
I might be wrong in several things ( correct me if I am ), since I am trying to understand REST and I am still learning.
To simplify things - you basically have two options:
1) Build Spring MVC application.
2) Build REST backend application.
In case of first option - within your application you will have both backend and frontend (MVC part).
In case of second option you build only backend application and expose it through REST API. In most cases, you will need to build another application - REST client for your application. This is more flexible application because it gives you opportunity to access your backend application from various clients - for example, you can have Android, IOS applications, you can have web application implemented using Angular etc...
Please note, that thins are not so simple, you can within one application have both REST backend and REST client etc... This is just very very simplified in order that you get some general picture. Hope this clarified a little things.
There is some additional clarification related to REST and views worth learning. From your question, I can see that you mean "view" in a sense of UI(user interface) and typical MVC usage. But "view" can mean different things in a different contexts.
So:
JSON can be considered as a view for data
JSON is a representation of the resource, just like HTML is
JSON doesn't have style (unless you are not using a browser
extension, which most the users are not using)
The browser is recognizing HTML as a markup language and applying a
style to it
Both are media types
Both JSON and HTML are data formats
Both can be transferred over the wire
This method returns a view
#RequestMapping("/home")
String home(Model model) {
return "home"; // resources\templates\home.html
}
This method Returns String
#RequestMapping(value = "/home")
#ResponseBody
public String home() {
return "Success";
}
If you annotate a method with #ResponseBody, Spring will use a json mapper to generate the response. Instead of annotating every method with #ResponseBody you can annotate your class with #RestController.
If you want to return a view, you need to annotate the class with #Controller instead of #RestController and configure a viewresolver. Bij default spring will use thymeleaf as a viewresolver if you have spring-web as a dependency on the classpath. The return type of the method is a String that references the template to be rendered. The templates are stored in src/main/resources/templates.
You can find a guide on the spring website: https://spring.io/guides/gs/serving-web-content/

How to Implement Role Based Authorization in MVC3 with Fluent NHibernate?

Our MVC3 application is using Fluent NHibernate and requires implementation of user login, authentication and authorization.
I've seen articles using the [Authorize] method in the controller classes. However, I'm not sure how this all works in our situation given that Fluent NHibernate is in use.
Can anyone share some suggestions as to how to make this work?
You could write a custom role provider implementing the RoleProvider class. In your custom implementation you of the RoleProvider class you could use whatever database access technology you want - FluentNhibernate or whatever. Basically you are interested in implementing the IsUserInRole method.
Then decorate your controllers/actions with the Authorize attribute:
[Authorize(Roles = "Admin")]
public ActionResult Foo()
{
return Content("Only administrators can see this message");
}
And here's another blog post that covers writing a custom role provider in more details.

MVC 3 And MEF and adding plug-ins to main application

I am a newbie to MEF and I am really mixed up! There are lot of useful articles out there and neat question and answers here in stackoverflow. I downloaded the example which #matthew-abbott has uploaded in his blog , but I dont know how to add new plug-ins or extension to extend the main web application, I mean like what you can see here.
Edited :
Also I use Entity Framework, Code First Approach and Unit of work for my data access layer application, what If my plug-ins needs data access and (I mean the plug-in has itself models) wants to use the DAL I created ? As you know every time the model changes, DbContext throws and error and tells re-create DB, Is there any way or other ORM which accepts extending DAL dynamically?
That particular example shows how we can integrate MEF with MVC3's new DependencyResolver which provides a service location mechanism for various extension points within the MVC architecture. There are a few other articles on my blog which detail more information about how a possible plugin architecture could work, these are available at:
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three
There are also a host of fantastic articles, my recommendations would be to also read:
ASP.NET MVC and the Managed Extensibility Framework (MEF) by Maarten Balliauw
Defining Web-scoped parts with MEF by Tim Roberts
MVC is a very flexible architecture, there are a myriad of ways it can be extended, but because of the nature of how ASP.NET applications run in IIS, you need to consider part lifetime very carefully. As an example, controllers can only be used for one request, so you could would need to ensure that your controllers have a specific CreationPolicy. Tim Robert's article on Web-scoped parts is a particularly good read.
Hope that is enough to point you in the right direction.
Edit: Because of the modular nature that MEF provides, it is important to ensure that your different layers are decoupled. You've specified that you are using Entity Framework, but the reality is, EF should likely only be used in your data layer. Typically the MVC architecture would promote view models over domain models. To that end, it is probably useful to use something similar to the repository pattern to define, e.g. here is a mock UserRepository:
[Export(typeof(IUserRepository))]
public class UserRepository : IUserRepository
{
public IEnumerable<UserViewModel> GetUsers()
{
// Get values here from EF as domain models
// And return them as view models?
}
}
Which we can export and inject into a controller:
[ExportController("User"), PartCreationPolicy(CreationPolicy.NonShared)]
public class UserController : Controller
{
private readonly IUserRepository _repo;
[ImportingConstructor]
public UserController(IUserRepository repo)
{
if (repo == null)
throw new ArgumentNullException("repo");
_repo = repo;
}
public ActionResult Index()
{
var users = _repo.GetUsers();
return View(users);
}
}
This is just a really simple example, but like many IoC containers, MEF also supports dependency injection. As long as a part provides a suitable export, it can be imported (either through property injection, or constructor injection) into another part at composition time.
My recommendation would be against exposing EF to your views, as this makes them explicitly dependent on it. By taking care to decouple and only expose the right types at the right layers, you architecture will become a lot more robust, flexible and testable, which makes maintaining it, and updating it a lot easier. As another quick example, here is how we could test our controller:
[Test]
public void UserController_CreatesViewResult_WithListOfUsers()
{
var mock = new Mock<IUserRepository>();
mock.Setup(m => m.GetUsers()).Returns(new[] { new UserViewModel { Name = "Matt" } });
var controller = new UserController(mock.Object);
var result = controller.Index();
Assert.That(result is ViewResult);
// Other assertions.
}
Because I haven't tightly coupled EF to my view, my controller is a lot more testable, I can mock a suitable repository and test where I need to.
The important thing is planning your architecture.

User Define Role and Right on Membership Provider on MVC

Dear All,
I am using the membership provider of MVC framework, Now i want to implement the Role and Right on My project, All the Role and Right is available on database so how can i implement the Role and Right? is there is any built in function which can i use? also i am using the Ado .net Data Entity Framework..
If I'm understanding what you want to do correctly, you have to annotate your Controller class or ActionResult with the Authorize attribute like this:
[Authorize(Roles="Domain Admins", Users="testuser")]
public class TestController : Controller {
}
Then as long as your membership provider is setup you should be good to go.
It may be worth mentioning that you can always check if a user is in a role with the following code.
User.IsInRole("Domain Admins");
If your using MVC2 then the default project template makes it easy. You should check out the AccountController and AccountModels in a default MVC2 template.
It sounds like you need a custom role provider:
http://davidhayden.com/blog/dave/archive/2007/10/17/CreateCustomRoleProviderASPNETRolePermissionsSecurity.aspx
http://msdn.microsoft.com/en-us/library/8fw7xh74.aspx
http://www.codeproject.com/KB/aspnet/WSSecurityProvider.aspx

Validation framework for business app built on Spring 2.5

What could the best strategy for writing validation layer for mid-enterprise level business application built on Spring 2.5
I know that Spring provides facility where we can implement Validator interface and write validation logic in validate method. But this will be restricted to only web requests coming through spring controller.
I would like to develop the validation framework which can be utilized during web-services calls.
In other words, the framework can remain and be called independently without the need of implementing Validator interface and then too it can be automatically integrated into Spring MVC flow.
Hope you get my point.
The Spring Validation framework can be used outside of Spring MVC. What WebServices Stack are you using? If you are using Spring-WS (Spring's Web Services stack) they have special instructions on how to set up the validator here:
http://static.springframework.org/spring-ws/sites/1.5/reference/html/server.html#d0e2313
If you are using some other stack, it is probably easier to implement something for that stack (or find one) that will use Spring's validation framework.
Recall that the Validator interface defines two methods:
boolean supports(Class clazz)
void validate(Object target, Errors errors)
The Object target is your form object, which is the whole object representing the page to be shown to the user. The Errors instance will contain the errors that will be displayed to the user.
So, what you need to do is define an intermediary that can be called with the specifics in your form that you want to validate which are also the same as in your web service. The intermediary can take one of two forms:
(probably the best):
public interface ErrorReturning {
public void getErrors(Errors errors);
}
(this can get ugly really fast if more than two states are added):
public interface ValidationObject {
public Errors getErrors(Errors errors);
public Object getResultOfWebServiceValidation();
}
I would suggest that the first approach be implemented. With your common validation, pass an object that can be used for web service validation directly, but allow it to implement the getErrors() method. This way, in your validator for Spring, inside your validation method you can simply call:
getCommonValidator().validate(partialObject).getErrors(errors);
Your web service would be based around calls to getCommonValidator().validate(partialObject) for a direct object to be used in the web service.
The second approach is like this, though the interface only allows for an object to be returned from the given object for a web service validation object, instead of the object being a usable web service validation object in and of itself.

Resources