Now that AS.NET WebApi2 has an integrated authorization mechanism using tokens.
How can we integrate this mechanism with Breeze.WebApi2. That is Breeze.WebApi2 and Microsoft.AspNet.Identity.
What I need is how to modify the project created using visual studio 2013 project wizard that is configured to use individual accounts in security into a breeze web api 2 server with the same security setup.
I tried it by creating a web api project with individual accounts security and then added breeze web api 2 server using nuget package but that was s bit confusing to me.
A sample code or application would be more useful for me to get started.
Thanks.
If you use the Authorize attribute you can also access the user data via the "User" variable.
[BreezeController]
[Authorize]
public class NorthwindIBModelController : ApiController {
[HttpGet]
public IQueryable<Customer> CustomerList() {
var userName = User.Identity.Name;
var filter = filter on customers;
var custs = ContextProvider.Context.Customers.Where({ some filter using userName});
}
}
Related
I am having a difficult time understanding how to add custom claims when using Windows authentication in a .Net MVC app.
The challenge here is to populate the users's identity with custom claims from the database on login, so as to avoid making a db call every time I want to check a custom authorization attribute. But the use of Windows auth complicates things for me, as there's no login method in which to put the code that populates the roles.
Is there a method to override, or some other way to hook into the Windows auth login process?
In .NET Core 2.0 you should use IClaimsTransformation.
For example:
public class CustomClaimsTransformer : IClaimsTransformation
{
public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
((ClaimsIdentity)principal.Identity)
.AddClaim(new Claim(claim.Name, claim.Value)); //your values
return Task.FromResult(principal);
}
}
And add this code to Startup.cs
...
services.AddMvc();
services.AddScoped<IClaimsTransformation,CustomClaimsTransformer>(); // Add this
I don't know how to do this in ASP.NET MVC :/.
This is my first answer here :).
Is it possible to use/call my Web API methods inside a MVC controller?
I have a Web Api to use in mobile and others plattaforms and I´m developing a .NET Mvc Website.
Does that architecture makes sense?
Thanks
Yes it's possible although if you're expecting to consume your API from a number of different clients I would suggest you create your API as a separate application that can then be managed/scaled accordingly.
Essentially you are referring to "dog-fooding" your own API, making your own web application no different to any other client.
We do something similar and have our MVC application call our API (using HttpClient). We also have a lot of client side code within the same application that calls the API directly using CORS.
We've had this architecture running in production for 2 years now without any issue.
Here is How I call my Web API controller from MVC controller:
public class invoiceController : ApiController
{
private myEntities db = new db1Entities();
// GET api/invoices
public IQueryable<invoices> Getinvoices()
{
return db.invoices;
}
}
inside separate MVC controller:
public ActionResult ShowInvoices()
{
var webApi = new invoicesController();
//this must return strongly typed object
var myarray = webApi.Getinvoices();
return View(myarray);
}
I design a simple online store. It has a product card, a list of products, the ability to add comments to the product, user registration, search products by price and other criteria. Maybe online store will have mobile clients (android and ios).
I want to try to work with RESTful. Is it normal to create this store, using RESTful? If it is normal, then I have a few questions.
When I create the usual sites, I write the following code:
public ActionResult Index()
{
var products = this.productRepository.GetAll();
return View(products);
}
How to change the architecture of the site, if I use RESTful. What must this method sent to client? Html only? And then the client has to execute AJAX request to the api to get the data?
RESTful web services is an HTTP-based services, any HTTP related applications can implement it by using WebApi,WCF, etc.
To build the online store project, of course you can use WebApi to build RESTful web services.
It's hard to say if using RESTful web services is normal or not, you can build an web application without building RESTful web services.
It only depends on your needs and preferences.
Let's say you're using WebApi to build RESTful web services for your project.
below is an example showing how you can implement it.
WebApi Controller
public class ProductsController : ApiController
{
public IEnumerable<Product> GetAllProducts()
{
return this.productRepository.GetAll();
}
}
MVC Action
Example 1: Calling Web API controller actions from MVC action
public ActionResult Index()
{
var webApi = new ProductsController();
return View(webApi.GetAllProducts());
}
Example 2: Populate all products in the view by calling Web API using Ajax
View:
<div id="contents"></div>
JS file
$(function() {
showAllProducts();
function showAllProducts() {
var url = "http://localhost:13131/api/Products/";
$.getJSON(url, function(result) {
$("#contents").append(result); // here you need do more than this.
});
}
});
What way to implement Web API depends on your need, there are a lot of way to implement it.
For your project, it's good to try different methods, you can learn more about it in the process.
Hope it helps.
I have an exmaple of mvc 4 web API , and I want to consume it in Excel 2010. whats the easiest way to do it? I am thinking to pass in the username and password as string parameter if solution need to be complicated.
[Authorize]
public class AccountBalanceApiController : ApiController
{
//http://localhost/FTAccounting/api/AccountBalanceApi?companyId=16&fiscalYear=2012
public Dictionary<int, TrialBalanceAccountSummaryModel> Get(int companyId, int fiscalYear)
{
return AccountBalance.GetTrialBalance(companyId, fiscalYear);
}
}
Update: Web service Authentication is not possible in Excel. Reference from http://cwebbbi.wordpress.com/2012/07/31/using-the-webservice-function-in-excel-2013/
web service Authentication is not possible in Excel. reference from http://cwebbbi.wordpress.com/2012/07/31/using-the-webservice-function-in-excel-2013/
In modern Excel you can use Get & Transform to connect to Web API with authorisation. Select Data tab, then in the Get & Transform group New Query -> From Other Sources -> From Web (Note: do not confuse this with 'From Web' button which is directly in the Get External Data group). Enter your endpoint URL (you can also define request headers here) and in the next step you will be asked for authentication method.
I currently have an ASP.NET MVC 4 website where members have an account and can log in using both Facebook and my own login form. I am then using FormsAuthentication.
I would next like to build an API, using WebAPI and expose some of my functionality to a mobile client I am planning on building.
I do not have any plans on having others consume my API, so this would just be for the client I build.
How would I go about implementing security on the WebAPI? Should I be using a token system where I can have a login form on the client, receive the credentials, log them in, and return a token which would be send back to the server on each call?
Should I implement oAuth on the server?
Try to be completely RESTful: use HTTP's built-in authentication system where authentication information is provided by the client in each request. You can also use HTTP Basic Authentication without any security concerns provided that you use SSL, otherwise HTTP Digest is also secure enough for this purpose.
You will need to implement your own HTTP Basic Authentication provider for ASP.NET, fortunately it's easy (and fun!).
It also beats other systems which require a signed URI using a querystring parameter, which is ugly and messes up lovely REStfulness, or carrying a token around (usually passed as a cookie).
Holy wars about how to do authentication in rest aside, you can just use forms authentication. If you are also using a web interface from the same site/domain and you have your authentication stuff well factored this is really convenient and easy.
you need a base class for your api controllers
public class MyApiControllerBase : ApiController
{
public MySecurityContextType SecurityContext { get; set; }
}
an ActionFilterAttribute
public class AuthenticationContextAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
MyApiControllerBase controller = actionContext.ControllerContext.Controller as MyApiControllerBase ;
if (controller != null)
{
var context = ((HttpContextBase)controller.Request.Properties["MS_HttpContext"]);
HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
controller.SecurityContext= ParseFormsAuthenticationTicket(ticket);
}
}
}
and code to create the ticket in the first place.
LogIn(HttpRequestBase httpRequest, string userName, string password)
{
var context = DoLoginLogic(userName,password);
FormsAuthentication.SetAuthCookie(context, usePersistentCookies);
}
Authorization will obviously need to be done in the controller methods.