Basic authorization

Here is the example of annotating attributes on EmployeeController:

    [Authorize]      
[Route("api/[controller]")]
public class EmployeeController : Controller
{
[HttpGet]
public List<Employee> Get()
{
return GetEmployees();
}

[HttpPost]
public bool Create(Employee employee)
{
return CreateEmployee(employee);
}

[HttpDelete]
public bool Delete(int id)
{
return DeleteEmployee(id);
}

[HttpPut]
public bool Update(Employee employee)
{
return UpdateEmployee(employee);
}
}
}

Annotating the authorize attribute on the Controller level will protect all the methods defined within it.

Alternatively, we can also apply the authorize attribute on the action level, as follows. In the following example, we have added the authorize attribute on Create, Update, and Delete operations:

      [Route("api/[controller]")] 
public class EmployeeController : Controller
{
[HttpGet]
public List<Employee> Get()
{
return GetEmployees();
}

[Authorize]
[HttpPost]
public bool Create(Employee employee)
{
return CreateEmployee(employee);
}

[Authorize]
[HttpDelete]
public bool Delete(int id)
{
return DeleteEmployee(id);
}

[Authorize]
[HttpPut]
public bool Update(Employee employee)
{
return UpdateEmployee(employee);
}
}
}

Action level attributes override the controller attribute. For example, if our EmployeeController is protected by annotating AuthorizeAttribute, we can make particular actions non-protected by using AllowAnonymousAttribute, as follows:

      [Authorize] 
[Route("api/[controller]")]
public class EmployeeController : Controller
{
[AllowAnonymous]
[HttpGet]
public List<Employee> Get()
{
return GetEmployees();
}

[HttpPost]
public bool Create(Employee employee)
{
return CreateEmployee(employee);
}

[HttpDelete]
public bool Delete(int id)
{
return DeleteEmployee(id);
}

[HttpPut]
public bool Update(Employee employee)
{
return UpdateEmployee(employee);
}
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.163.175