Get Access Token with BreezeSharp - breeze

I need to use EntityQuery in BreezeSharp to get Access Token from my Breeze WebAPI
I have a class called TokenResponseModel for deserializing my json from the server as follows:
using Newtonsoft.Json;
namespace CMIS.Integration.Common
{
class TokenResponseModel
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("userName")]
public string Username { get; set; }
[JsonProperty(".issued")]
public string IssuedAt { get; set; }
[JsonProperty(".expires")]
public string ExpiresAt { get; set; }
}
}
I have the following code to run:
EntityQuery query=EntityQuery.From("Token",new TokenResponseModel()).
WithParameters(new Dictionary<string,object>{{"grant_type","password"},{"username","my_username"},{"password","my_password"}});
EntityManager mng = new EntityManager(baseUrl);
var tokenobject = await query.Execute(mng);
When I run it, I Get an error. It requires metadata which is not there for the "/Token" method on the server.
How Can I call it with BreezeSharp.
With RestSharp I can do it as follows:
RestRequest request = new RestRequest("/Token", Method.POST);
request.AddParameter("grant_type", "password");
request.AddParameter("username", "my_username");
request.AddParameter("password", "my_password");
RestClient client = new RestClient(baseUrl);
var response = client.Execute<AccessToken>(request);
And this works fine.
Thanks
More Explanation:
What I want to say is that sometimes I just need to get the result from the breeze server just i a JSON format. I don't want it mapped to any objects on the client. A good example is my case for authenticating a user using the Token method. I know how to parse the JSON myself. I just want breeze to bring the result from the call below:
string baseUrl = "http://myserver_url/NHIFService/";
EntityQuery query = EntityQuery.From<string>("Token").WithParameters(new new Dictionary<string, object> { { "grant_type", "password" }, { "username", "my_username" }, { "password", "my_password" } });
EntityManager mng = new EntityManager(baseUrl);
var tokenobject = await query.Execute(mng);
I want to be able to do this because sometimes I return anonymous objects from the server that do not have a match on the client or server.
Can breese sharp allow me to do this without caring about the metadata. Or how can I supress metadata fetching.
Thank you.

After going through the BreezeSharp Source Code I came with the solution for doing what I wanted. The guys at IdeaBlade have created this DataService class that enables returning RAW JSON from the server without even caring about the Metadata. Here is how I did it:
string token = await AuthenticationHelper.GetAccessToken();
string baseUrl = "http://my_server_url/appname/breeze/my_controller/";
DataService ds = new DataService(baseUrl);
string resourcePath = string.Format("GetCardDetails?CardNo={0}", cardNoTextEdit.EditValue);
ds.HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
string result=await ds.GetAsync(resourcePath);
Congratulation guys Breeze Sharp is awesome.

Related

How can I pass datetime from API to postgresql db which receives timestamp without zone time?

I trying to pass a datetime value from MVC API net Core to PostgreSQL database.
In the model I'm using data type string for the datetime (fechahora) and the db has data type timestamp without zone time.
Model:
public class Feedback
{
public int id { get; set; }
public string fechahora { get; set; }
public string detalle { get; set; }
}
My function:
public async Task<bool> InsertFeedback(Feedback feedback)
{
var db = dbConnection();
var sql = #"INSERT INTO public.tb_feedback (fechahora,detalle)
VALUES #fechahora,#detalle";
var result = await db.ExecuteAsync(sql, new { feedback.fechahora, feedback.detalle });
return result > 0;
}
If I execute the same query in the database it works.
Also if a consult using GET from postman works too
GET postmand
but this happens when I try to
POST
The issue is directly with timestamp, because I have other controller all working fine with no dates.
I found a solution, first I was missing the brackets but then I also added the to_timestamp and the correct format
var db = dbConnection();
var sql = #"INSERT INTO public.tb_feedback (fechahora,detalle)
VALUES (to_timestamp(#fechahora,'DD/MM/YYYY HH24:MI:SS'),#detalle)";
var result = await db.ExecuteAsync(sql, new { feedback.fechahora, feedback.detalle });
return result > 0;
Json POST
{
"fechahora": "02/05/2021 14:00:00",
"detalle": "prueba"
}

Endpoint Not found MVC

I'm working with a very weird endpoint,
Now the data I post to my endpoint is the scorecardId and the DashboardConfig and the rest of my data is populated via the backend, which is the UserId and the DateCreated, Now I need to do a get request for the specific user and I did something like this:
#region Public Methods
[HttpGet]
[Route("GetbyUserID")]
[ValidateModel]
public IHttpActionResult GetbyUserID(Guid UserID)
{
UserID = this.GetUserId();
var config = _prefentialDashboardConfigService.GetByUserID(UserID);
return Ok(config);
}
My model:
public Guid ScorecardId { get; set; }
public Guid UserId { get; set; }
public DateTime DateCreated { get; set; }
public string DashboardConfig { get; set; }
My CRUD:
public PrefentialDashboardConfig GetByUserID(System.Guid UserId, params string[] includes)
{
return Repository.SingleOrDefault<PrefentialDashboardConfig>(config => config.UserId == UserId, includes);
}
}
My ICRUD:
T SingleOrDefault<T>(Expression<Func<T, bool>> where, params string[] includes) where T : class;
And in my front end I just called the get request but it gives me a 404 resource not found error. I call my end point like this in knockout:
var test = PreferentialProcurementDashboardApi.GetbyUserID();
//For testing purposes
console.log("You got it right!" + JSON.stringify(test));
What would be the best way to get my data to the frontend console by the UserId which is taken from my backend?
only guessing, you are probably not passing the UserId when you are doing the http get request.
var test = PreferentialProcurementDashboardApi.GetbyUserID();
probably should be
var test = PreferentialProcurementDashboardApi.GetbyUserID(5);
check the network tab in the browser dev tools to make sure that there are parameters are being passed to the backend

Ouath 2.0 with Asp.net Web Api 2 with only external login like google etc

I am trying to implement Oauth 2.0 security integration with Asp.net web api 2 but only with external logins like google.I am pretty new for Oauth thing.
Can any one suggest any good tutorial/ example with only external login.
I do not want local user to register etc.
Google describes all the options pretty well on their website Using OAuth 2.0 to Access Google APIs
The most important steps are:
Register your application at Google Developer Console
Enable all your required scopes
Specify the allowed callback url to your website
Basically it works like this:
You redirect the user to your /api/Account/Login page
This Action method will redirect the user to the Google login page
User logs in and gets redirected to the callback url you specified (and approved in the Developer Console)
This callback url Action method will ask Google for a token based on the authorization code.
Following code snipped should get you started:
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
private readonly string _clientId = "YourCliendId";
[Route("Login")]
public HttpResponseMessage GetLogin()
{
string scope = HttpUtility.UrlEncode("Space Seperated list of scopes");
string redirectUri = HttpUtility.UrlEncode("http://YourWebsiteURL/api/Account/OAuthCallback");
string accessType = "Either online or offline";
string requestUri = string.Format("https://accounts.google.com/o/oauth2/auth?response_type=code&client_id={0}&redirect_uri={1}&scope={2}&access_type={3}&approval_prompt=auto&include_granted_scopes=true", _clientId, redirectUri, scope, accessType);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.MovedPermanently);
response.Headers.Location = new Uri(requestUri);
return response;
}
[Route("Logout")]
public HttpResponseMessage GetLogout()
{
//Optionally if you need to be able to logout...
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("https://accounts.google.com/logout");
return response;
}
[Route("OAuthCallback")]
public HttpResponseMessage GetOAuthCallback(string error)
{
//This would be a nice place to include some logging...
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://YourWebsiteURL");
return response;
}
[Route("OAuthCallback")]
public HttpResponseMessage GetOAuthCallback(string code, string scope)
{
string redirectUri = HttpUtility.UrlEncode("http://YourWebsiteURL/api/Account/OAuthCallback");
string postMessage = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code", code, _clientId, "YourGoogleSecretCode", redirectUri);
string jsonMessage;
using (WebClient client = new WebClient())
{
//Convert the authorization code to a token
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded; charset=utf-8";
jsonMessage = client.UploadString("https://accounts.google.com/o/oauth2/token", "POST", postMessage);
}
Token token = JsonConvert.DeserializeObject<Token>(jsonMessage);
//Do something with the token. E.g. put it in a cookie / header ... and pass it to the client.
}
}
public class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
public class TokenInfo
{
[JsonProperty("issued_to")]
public string IssuedTo { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("user_id")]
public string UserId { get; set; }
[JsonProperty("scope")]
public string Scope { get; set; }
[JsonProperty("expires_in")]
public int ExpiresIn { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("verified_email")]
public bool VerifiedEmail { get; set; }
[JsonProperty("access_type")]
public string AccessType { get; set; }
}
BTW. If you need to later on validate the token you can use the following code:
string requestUri = string.Format("https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={0}", token.AccessToken);
string tokenInfoMessage;
using (WebClient client = new WebClient())
{
tokenInfoMessage = client.DownloadString(requestUri);
}
TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(tokenInfoMessage);
//Don't forget to validate the Audience and Scope, because the token might be a valid token (but not meant for your website).
if (tokenInfo.Audience == _clientId && tokenInfo.Scope.Contains("All the scopes that you provided") && tokenInfo.UserId == "TheGoogleUserIdYouWantToCheck")
{
//Looks valid, so continue with whatever you want to do...
}

MVC Web API Post Does not get called from HttpClient

I have the following Model
public class Customer
{
public string Name
{
get;set;
}
public string Address
{
get;
set;
}
}
The following WebAPI Method
[Route("PostCustomer")]
[HttpPost]
public Customer PostCustomer([FromBody]Customer c)
{
return c;
}
The following client code
Customer cust = new Customer() { Name = "abcd", Address = "test" };
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:11581");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync<Customer>("api/values/PostCustomer", cust);
The WebAPI Method never gets called and the response I get from the Web API says no content. When I try the same for a get it works fine.

Creating RESTful architecture to communicate between ASP.NET web app and MVC 3 App using JSON

I need to take GET fields from my asp.net web app (first name and last name). It needs to send that data from frontend(asp.net web app) using JSON to MVC 3 app. MVC 3 App would communicate with database, retrieve values and should serialize them into json object and POST to the front end(ASP.NET web app). Can anyone explain with a sample code how I would accomplish this?
You could use the WebClient class. It allows you to send HTTP requests to any web application. As far as the JSON part is concerned you will need a JSON serializer. You could use the built-in JavaScriptSerializer class or a third party such as Json.NET.
So let's suppose that you have the following controller action in your ASP.NET MVC 3 application that you want to invoke:
[HttpPost]
public ActionResult Foo(Bar bar)
{
...
return Json(new
{
status = "OK"
});
}
where the Bar class contains some properties (could be simple or complex types):
public class Bar
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Now you could invoke it like this from the client side:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(new
{
firstName = "first",
lastName = "last"
});
var resultJson = client.UploadString("http://example.com/foo", json);
var result = serializer.Deserialize<Result>(resultJson);
}
where you would define the Result class to match the JSON structure returned by the application:
public class Result
{
public string Status { get; set; }
}

Resources