This is truely notes to self sorry if this is criptic.
Adding the [authorize] attribute to the the controller means that the user must be logged in inorder to access anything in the controller. If you want to give user access to specificed areas of the contoller without being logged in you can add the [AllowAnonymous] attribute to the ActionResult method such as:
[Authorize]
public class HomeController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
You can also specify exactly who has acsess to different areas of the the site by either specifiying a specific user(s) or a role(s). This is achieved by using the following attributes:
[Authorize(roles=”Administrators”)]
[Authorize(users=”jseely, anotherUser”)]
You can have mulitpler users and roles as long as you separate them with a comma. Using specific users may not be the best idea as that user may leave the company and you would have to change the code. Roles is a better way to go as you can add and remove users from a role.
Seeding the Database with Entity Framework
Since I haven’t covered working with Entity Framework in ANY of my posts so you will need to have an understanding of the code fist approach to creating a database with Entity Framework.
Inorder to use the Update-Database command in the Package Manager Console you will nee to have something similar to the following you your web.config file.
In web.config:
<roleManager enabled=”true” defaultProvider=”simple”>
<providers>
<clear/>
<add name =”simple” type=”WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData”/>
</providers>
</roleManager>
<membership defaultProvider=”simple”>
<providers>
<clear/>
<add name =”simple” type=”WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData”/>
</providers>
</membership>
In your View
What if you have something in your view that only admins can see? Maybe it’s a link or maybe it’s an employee’s pay so only people in the HR role is allowed to see this informaiton. You don’t want to write a new view just for this role so how can you determine if information should be shown. You simply need to check to see if the user has the correct role. This can be accomplished by:
@if(User.IsInRole(“admin”))
{
<h1>Admin </h1>
}
else{
<h1> NOT an Admin </h1>
}