I'm using asp.net boilerplate for my website. There I have standard authentication from aspnetboilerplate/module-zero(OWIN).
But now I need athentication for my windows phone app(wp8.1)
I was trying configure my application for authorization with bearer but I failed..
How configurate asp.net boilerplate application for my windows phone app auth?
In windows phone app I send post to my web api like this:
public static async Task<TokenResponseModel> GetBearerToken(string siteUrl, string Username, string Password)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(siteUrl);
client.DefaultRequestHeaders.Accept.Clear();
HttpContent requestContent = new StringContent("grant_type=password&username=" + Username + "&password=" + Password, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage responseMessage = await client.PostAsync("Token", requestContent);
if (responseMessage.IsSuccessStatusCode)
{
string jsonMessage;
using (Stream responseStream = await responseMessage.Content.ReadAsStreamAsync())
{
jsonMessage = new StreamReader(responseStream).ReadToEnd();
}
TokenResponseModel tokenResponse = (TokenResponseModel)JsonConvert.DeserializeObject(jsonMessage, typeof(TokenResponseModel));
return tokenResponse;
}
else
{
return null;
}
}
But what should I do in WebApi? How auth and next response bearer and how auth in next step using bearer when on class i have [AbpAuthorize]?
This now documented and implemented in module zero template
code:
In module WebApi:
Configuration.Modules.AbpWebApi().HttpConfiguration.Filters.Add(new HostAuthenticationFilter("Bearer"));
In controller WebApi:
[HttpPost]
public async Task<AjaxResponse> Authenticate(LoginModel loginModel)
{
CheckModelState();
var loginResult = await GetLoginResultAsync(
loginModel.UsernameOrEmailAddress,
loginModel.Password,
loginModel.TenancyName
);
var ticket = new AuthenticationTicket(loginResult.Identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
return new AjaxResponse(OAuthBearerOptions.AccessTokenFormat.Protect(ticket));
}
documentation: http://aspnetboilerplate.com/Pages/Documents/Zero/Startup-Template#token-based-authentication
Related
I am adding CF Turnstile recaptcha to my asp.net core web api for our contact us form and I am curious what IP address I should be using for this verification process. My code is as follows:
var dictionary = new Dictionary<string, string>
{
{ "secret", reCaptchaKey },
{ "response", customerInquiry.Token }
};
var postContent = new FormUrlEncodedContent(dictionary);
HttpResponseMessage recaptchaResponse = null;
string stringContent = "";
// Call recaptcha api and validate the token
using (var http = new HttpClient())
{
recaptchaResponse = await http.PostAsync("https://challenges.cloudflare.com/turnstile/v0/siteverify", postContent);
stringContent = await recaptchaResponse.Content.ReadAsStringAsync();
}
The example code on CF shows the following for their node.js ( I assume) implementation:
formData.append('secret', SECRET_KEY);
formData.append('response', token);
formData.append('remoteip', ip);
I am working on an asp.net Web API and I have an web application that consumes this api.
Right now it is working perfectly since I don't have the [Authorize] part on my api controller.
So, if I want to secure this api, my web application will not be able anymore to fetch data from the API because it is not authorized.
So how can I send the token generated from my API to my web app and to allow it to fetch the needed data?
-I am using postman for testing my app;
-my api return jwt token;
-I am not really familiar with http headers.
My consuming web application controller :
public ActionResult Index()
{
IEnumerable<OperatorClass> OperatorObject = null;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44304/api/");
var ApiOpController = client.GetAsync("data");
client.DefaultRequestHeaders.Add("Authorization", "Bearer"+"");
ApiOpController.Wait();
var resultDisplay = ApiOpController.Result;
if (resultDisplay.IsSuccessStatusCode)
{
var readTable = resultDisplay.Content.ReadAsAsync<IList<OperatorClass>>();
readTable.Wait();
OperatorObject = readTable.Result;
}
else
{
OperatorObject = Enumerable.Empty<OperatorClass>();
ModelState.AddModelError(String.Empty, "No records found");
}
return View(OperatorObject);
}
My web API controller
[Authorize]
[HttpGet]
public IHttpActionResult GetOperators()
{
SchoolEntity myEntity = new SchoolEntity ();
IList<OperatorClass> OperatorObject = myEntity.Operator.Include("Operator").Select(x => new OperatorClass()
{
name = x.name,
lastname = x.lastname,
mobile = x.mobile,
username = x.username,
password = x.password
}).ToList<OperatorClass>();
return Ok(OperatorObject);
}
string token = <Your token>
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
this should work for you.
To be able to use your MVC controller, you need to store the token when it returns.
One way to do it is to store it using Session.
Assuming you are using sign in to get the token, anytime you sign in successfully you can store the token using the session. See below.
//For brevity after successful login
string myToken = <token returned from api>
HttpContext.Session.SetString("token", myToken);
//other codes
then you can use this in all of your controllers.
public async Task<ActionResult> Index()
{
IEnumerable<OperatorClass> OperatorObject = null;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44304/api/");
//note here
var token = HttpContext.Session.GetString("token");
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
//ApiOpController.Wait();
var resultDisplay = await client.GetAsync("data");
if (resultDisplay.IsSuccessStatusCode)
{
var readTable = await resultDisplay.Content.ReadAsAsync<IList<OperatorClass>>();
//readTable.Wait();
OperatorObject = readTable;
}
else
{
OperatorObject = Enumerable.Empty<OperatorClass>();
ModelState.AddModelError(String.Empty, "No records found");
}
return View(OperatorObject);
}
I'm starting to use PayPal for payments with .net Core. I created a sandbox app and checked client id and secret. I get an error at content
"{"error":"invalid_client","error_description":"Client Authentication failed"}"
Code:
private async Task<PayPalAccessToken> GetPayPalAccessTokenAsync(HttpClient httpClient)
{
byte[] bytes = Encoding.GetEncoding("iso-8859-1")
.GetBytes($"{_configuration["PayPal:clientId"]} : {_configuration["PayPal:secret"]}");
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "/v1/oauth2/token");
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Basic", Convert.ToBase64String(bytes));
var form = new Dictionary<string, string>
{
["grant_type"] = "client_credentials"
};
requestMessage.Content = new FormUrlEncodedContent(form);
HttpResponseMessage responseMessage = await httpClient.SendAsync(requestMessage);
string content = await responseMessage.Content.ReadAsStringAsync();
PayPalAccessToken accessToken = JsonConvert.DeserializeObject<PayPalAccessToken>(content);
return accessToken;
}
Setting:
"PayPal": {
"clientId": "xxx",
"secret": "xxx",
"urlAPI": "https://api-m.sandbox.paypal.com",
"returnUrl": "https://localhost:44370/cart/success",
"cancelUrl": "https://localhost:44370/cart/cancel"
}
And here is Code I followed https://gist.github.com/jakejscott/1b829ca1c9449e4788710867f346e90f
Full my code https://paste.mod.gg/ayoqinotis.csharp
What is the problem that I am facing?
I'm trying to implement ROPC flow in asp.net api . Can you please guide me on how to achieve this properly in ASP.net core using built in authentication library. If it is not possible what are the alternatives
I'm able to get the access token using http call to azure AD token endpoint. But i'm not able to validate the token using built in authentication library
can we implement this without the HTTP call , but using built in library.
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
Im using the below code snippet to get the access token
private async Task<string> GetTokenAsync(string username, string password)
{
string grantType = "password";
string tenantId = Configuration["AzureAdNative:TenantId"];
string clientId = Configuration["AzureAdNative:ClientId"];
string resource = Configuration["AzureAdNative:Resource"];
string endpoint = "https://login.microsoftonline.com/" + tenantId + "/oauth2/token";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var dict = new Dictionary<string, string>();
dict.Add("grant_type", grantType);
dict.Add("client_id", clientId);
dict.Add("username", username);
dict.Add("password", password);
dict.Add("resource", resource);
var req = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new FormUrlEncodedContent(dict) };
var res = await client.SendAsync(req);
string result = res.Content.ReadAsStringAsync().Result;
var jwt = JObject.Parse(result);
return result;
// return jwt.GetValue("access_token").ToString();
}
getting unauthorised 401 error while validating with above code. access token is being sent in the authorization header (eg: Authorization : Bearer e4dgkddskdsdk).
I am trying to use office365 api in my single page .net application not an mvc. I got the source code for mvc .net project C# in the website itself.
public async Task<ActionResult> SignIn()
{
string authority = "https://login.microsoftonline.com/common";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"];
AuthenticationContext authContext = new AuthenticationContext(authority);
// The url in our app that Azure should redirect to after successful signin
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Generate the parameterized URL for Azure signin
Uri authUri = await authContext.GetAuthorizationRequestUrlAsync(scopes, null, clientId, redirectUri, UserIdentifier.AnyUser, null);
// Redirect the browser to the Azure signin page
return Redirect(authUri.ToString());
}
// Note the function signature is changed!
public async Task<ActionResult> Authorize()
{
// Get the 'code' parameter from the Azure redirect
string authCode = Request.Params["code"];
string authority = "https://login.microsoftonline.com/common";
string clientId = System.Configuration.ConfigurationManager.AppSettings["ida:ClientID"]; ;
string clientSecret = System.Configuration.ConfigurationManager.AppSettings["ida:ClientSecret"]; ;
AuthenticationContext authContext = new AuthenticationContext(authority);
// The same url we specified in the auth code request
Uri redirectUri = new Uri(Url.Action("Authorize", "Home", null, Request.Url.Scheme));
// Use client ID and secret to establish app identity
ClientCredential credential = new ClientCredential(clientId, clientSecret);
try
{
// Get the token
var authResult = await authContext.AcquireTokenByAuthorizationCodeAsync(
authCode, redirectUri, credential, scopes);
// Save the token in the session
Session["access_token"] = authResult.Token;
// Try to get user info
Session["user_email"] = GetUserEmail(authContext, clientId);
return Redirect(Url.Action("Inbox", "Home", null, Request.Url.Scheme));
}
catch (AdalException ex)
{
return Content(string.Format("ERROR retrieving token: {0}", ex.Message));
}
}
I converted the code to vb.net and i am receiving bad request error stating that my application is not supported for this api version when executed. The code is in WebForm1.aspx and the redirect uri link is to webform2.aspx
Private Sub SignIn()
Dim authority As String = "https://login.microsoftonline.com/common"
Dim clientId As String = System.Configuration.ConfigurationManager.AppSettings("ida:ClientID")
Dim authContext As New AuthenticationContext(authority)
Dim redirectUri As New Uri("http://localhost:26683/WebForm2.aspx")
Dim authUri As Uri = authContext.GetAuthorizationRequestURL("https://outlook.office.com/mail.read", clientId, redirectUri, UserIdentifier.AnyUser, Nothing)
Response.Redirect(authUri.ToString())
End Sub
How ever i have registered the application.In fact when i used the same client id and client secret for the mvc application it is executed without any error but when i use it in my single web application it throws this error.
Please help.What am i doing wrong