web api 2 - Oauth2 Bearer token access is forbidden - oauth-2.0

I have an mvc 5 application with an web api 2. (.NET 4.6)
I implemented the oauth2 configuration next to the authentication for my mvc app (app.UseCookieAuthentication) :
OAuthAuthorizationServerOptions OAuthServerOptions = new
OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/token"),
Provider = new AspNetIdentityOAuthAuthorizationServerProvider(),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(1000),
};
app.UseOAuthBearerTokens(OAuthServerOptions);
My apis are protected with the Authorize Attribute (global filter).
I use the client credentials grant
I followed these two articles (that are the same)
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
https://mitchelsellers.com/blogs/2017/05/10/adding-webapi-oauth-authentication-to-an-existing-project
I'm able to get a token for my user, but when I want to use the token to access my Api, I get a 403 forbidden error
HttpClient client = new HttpClient();
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("grant_type", "client_credentials");
parameters.Add("client_id", "4rclFahG7gho8erzbsmTbw==");
parameters.Add("client_secret", "IBSqiYb0kT/lzV0gpQsPxkUDI9ztu0dhHWDe4VQDzKGYm2pl+75sMVfEsoGo4FAxFm0qZUFcDrVMrfqYhn2bzw==");
var content = new FormUrlEncodedContent(parameters);
try
{
HttpResponseMessage result = client.PostAsync("http://localhost:49594/oauth/token", content).Result;
string jsonResult = result.Content.ReadAsStringAsync().Result;
var resultObject = JsonConvert.DeserializeObject<TokenResult>(jsonResult);
var accessToken = resultObject.access_token;
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
result = client.GetAsync("http://localhost:49594/api/v1/echo?id=myt
estvalue").Result;
// RESULT is 403 - Forbidden
I tested with postman as well, and the result is the same.
did anyone experienced the same problem ?
do you know what I' missing ?
Update :
It's working if I deploy my application on a server (azure app services) but still not on my machine

I found the reason of my issue !
I'm using stuntman (https://rimdev.io/stuntman/) for my dev and I forgot to configure it for oauth ...
This line was missing :
StuntmanOptions.AllowBearerTokenPassthrough = true;

Related

Token verification failed : keycloak and docker

i'm developing a netCore API where i have to authenticate applications with a token. Client provide me the token and my API validate it from Keycloak. Everything is Ok, the problem is where i build my app in a Docker Container. Where the token is from an external application this is invalid, but if i personally get the token from keycloak then is valid.
I think maybe is timezone, but i tried to change the timezone of my PC and get the token with postman but is not valid too.
`var client1 = new HttpClient(clientHandler);
var request1 = new HttpRequestMessage();
request1.RequestUri = new Uri(conf["VALIDATION"]);
request1.Method = HttpMethod.Get;
var a = JObject.Parse(result);
Console.WriteLine("access_token=> "+ a.GetValue("access_token").Value<string>());
request1.Headers.Add("Authorization", "Bearer "+token);
var formList1 = new List<KeyValuePair<string, string>>();
request1.Content = new FormUrlEncodedContent(formList1);
var response1 = await client1.SendAsync(request1);
var result1 = await response1.Content.ReadAsStringAsync();
Console.WriteLine(result1);`
the result is:
{"error":"invalid_token","error_description":"Token verification failed"}

Sign In using raw HttpRequestMessage in ASP.NET MVC

I have been testing some code to sign in users to their Microsoft/school/work accounts using raw HttpRequestMessage and HttpResponseMessage. I know there are libraries available to do this but I want to test the raw approach as well (especially usage of refresh tokens), while looking for the right library to handle it.
I'm currently learning authentication, with limited knowledge of ASP.NET/Core.
I'm following this guide: https://learn.microsoft.com/en-us/graph/auth-v2-user
I've just modified the SignIn() method in AccountController in an example project that used more high level libraries to sign in.
I'm requesting an authorization code.
The SignIn() code:
public void SignIn()
{
using (var httpClient = new HttpClient())
{
try
{
var tenant = "my tenant id";
var clientId = ConfigurationManager.AppSettings["ida:AppID"];
var responseType = "id_token+code";
var redirectURI = ConfigurationManager.AppSettings["ida:RedirectUri"];
var responseMode = "form_post";//query";
var appScopes = ConfigurationManager.AppSettings["ida:AppScopes"];
var scopes = $"openid profile offline_access {appScopes}";
var state = "12345";
//var prompt = "consent";
var url = string.Format("https://login.microsoftonline.com/{0}/oauth2/v2.0/authorize", tenant);
var body = string.Format("client_id={1}&response_type={2}&redirect_uri={3}&response_mode={4}&scope={5}&state={6}", tenant, clientId, responseType, redirectURI, responseMode, scopes, state);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded");
var response = httpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).Result;
var content = response.Content.ReadAsStringAsync().Result;
}
catch (Exception ex)
{
}
}
//if (!Request.IsAuthenticated)
//{
// // Signal OWIN to send an authorization request to Azure
// Request.GetOwinContext().Authentication.Challenge(
// new AuthenticationProperties { RedirectUri = "/" },
// OpenIdConnectAuthenticationDefaults.AuthenticationType);
//}
}
I'm just returning void from the method now because I'm not sure what I should return yet.
Debugging and looking at the response variable, the status code is 200, and has some other information to it. However, the content of the HttpResponseMessage, when I paste it into a file and opening it in a browser, displays (or redirects to) https://login.microsoftonline.com/cookiesdisabled, which shows a message saying that I could not be logged in because my browser blocks cookies. However, I don't think this really is the case.
How can I resolve this and have the user log in and consent, and get the authorization code?
I couldn't really find any example in ASP.NET that uses this raw approach. Is it not recommended?
You should fistly understand how OAuth 2.0 authorization code flow works in Azure AD V2.0 :
Microsoft identity platform and OAuth 2.0 authorization code flow
The general process would be like :
When login in client application, user will be redirect to Azure AD login endpoint(https://login.microsoftonline.com/{0}/oauth2/v2.0/authorize) and provides info like which client(client_id) in which tenant(tenant id) user wants to login , and redirect back to which url(redirect_uri) after successful login.
User enter credential , Azure AD validate credential and issue code and redirect user back to redirect url provided in step 1 (Also match one of the redirect_uris you registered in the portal).
The client application will get the code and send http post request with code to acquire access token .
So if you want to manally implement the code flow in your application , you can refer to below code sample :
public async Task<IActionResult> Login()
{
string authorizationUrl = string.Format(
"https://login.microsoftonline.com/{0}/oauth2/v2.0/authorize?response_type=code&client_id={1}&redirect_uri={2}&scope={3}",
"tenantID", "ClientID", "https://localhost:44360/Home/CatchCode",
"openid offline_access https://graph.microsoft.com/user.read");
return Redirect(authorizationUrl);
}
private static readonly HttpClient client = new HttpClient();
public async Task<ActionResult> CatchCode(string code)
{
var values = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "client_id", "XXXXXX"},
{ "code", code},
{ "redirect_uri", "https://localhost:44360/Home/CatchCode"},
{ "scope", "https://graph.microsoft.com/user.read"},
{ "client_secret", "XXXXXXXXXXX"},
};
var content = new FormUrlEncodedContent(values);
//POST the object to the specified URI
var response = await client.PostAsync("https://login.microsoftonline.com/cb1c3f2e-a2dd-4fde-bf8f-f75ab18b21ac/oauth2/v2.0/token", content);
//Read back the answer from server
var responseString = await response.Content.ReadAsStringAsync();
//you can deserialize an Object use Json.NET to get tokens
}
That just is simple code sample which will get Microsoft Graph's access token , you still need to care about url encode and catch exception , but it shows how code flow works .

How to get an ACS app-only access token for Project Online

I'm trying to get an AppOnly access token for use in the Authorization Bearer header of my request to a REST endpoint in Project Online (SharePoint). Following is a snippet of the code that I was using to retrieve the access token.
private OAuth2AccessTokenResponse GetAccessTokenResponse()
{
var realm = TokenHelper.GetRealmFromTargetUrl([[our_site_url]]);
var resource = $"00000003-0000-0ff1-ce00-000000000000/[[our_site_authority]]#{realm}";
var formattedClientId = $"{ClientId}#{realm}";
var oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(
formattedClientId,
ClientSecret,
resource);
oauth2Request.Resource = resource;
try
{
var client = new OAuth2S2SClient();
var stsUrl = TokenHelper.AcsMetadataParser.GetStsUrl(realm);
var response = client.Issue(stsUrl, oauth2Request) as OAuth2AccessTokenResponse;
var accessToken = response.AccessToken;
}
catch (WebException wex)
{
using (var sr = new StreamReader(wex.Response.GetResponseStream()))
{
var responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
}
I keep getting 403 Forbidden as the response from the server, even if I include site collection admin credentials with my request. Does anyone out there have any ideas?
After creating a support ticket with Microsoft to figure this out we eventually decided to move away from using app permissions for console application authorization.
Our workaround was to create SharePointOnlineCredentials object using a service account, and then get the Auth cookie from the credentials object to pass with our WebRequest. This solution came from scripts found here: https://github.com/OfficeDev/Project-REST-Basic-Operations

mvc and web.api authorisation using oauth

Seems like I am asking the same question that many have but can not fit everything together.
I have a standard MVC application configured with Oauth using the standard Identity DB, the user signs in and that all works fine, I then want to call the Web.API application as an authenticated user. From my research I have added the bearer token to the httpclient thinking that this would somehow be authorized in the web.api application I have set the Web.API application to point to the same identity db but im not sure what i am missing. I've spent days on this and no luck so any samples would be much appreciated.
the code to get the bearer token is
protected string GetToken()
{
var identity = new ClaimsIdentity(Startup.OAuthBearerOptions.AuthenticationType);
identity.AddClaim(new Claim(ClaimTypes.Name, User.Identity.Name));
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, User.Identity.GetClaimValue(ClaimTypes.NameIdentifier.ToString())));
AuthenticationTicket ticket = new AuthenticationTicket(identity, new AuthenticationProperties());
var currentUtc = new SystemClock().UtcNow;
ticket.Properties.IssuedUtc = currentUtc;
ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(30));
string accessToken = Startup.OAuthBearerOptions.AccessTokenFormat.Protect(ticket);
return accessToken;
}
the call to the Web.APi is
var token = GetToken();
string uri = UriEASOnlineApi + EASOnlineWebAPI.SignErectors;
List<SignErector> result;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var task = await client.GetAsync(uri);
if (task.IsSuccessStatusCode)
{
var jsonString = await task.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<List<SignErector>>(jsonString);
}
else
{
throw new Exception($"failed: {task.StatusCode}");
}
}
First of all you need to know how authentication is done in WebApi. Then if you have working example of call to this WebApi e.g. from Postman or Fiddler you can compare manual request with the one you create programmatically from MVC application.

MVC 5 application - implement OAuth Authorization code flow

Based on this tutorial http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server, I have created an Authorization Server, a Resource Server and a MVC Client.
The MVC Client has a Controller which gets some data from the Resource Server. The Resource Server requires authentication. The MVC Clients gets an authorization code from the Authorization Server and Redirects the user to the Authorization Server for authentication. Finally the MVC Clients exchanges the authorization code for a Access token to Access the Resource Server. This is the Authorization code flow as described by the OAuth 2 protocol. This works fine.
Now, I have the requirement to make a Controller of the MVC Client itself require Authentication. I can not find a tutorial for this.
I added
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
to my Startup.Auth.cs.
I assume, I need to setup the Options to Redirect to the Authorization Server. I can also set the Provider on the Options:
app.UseOAuthBearerAuthentication(new Microsoft.Owin.Security.OAuth.OAuthBearerAuthenticationOptions()
{
Provider = new OAuthBearerAuthenticationProvider()
});
But I am also stuck on implementing the events of the Provider.
Can anybody guide me in the right direction? Or are there any tutorials which might help me?
I ended up with a solution based on these two articles from Brock Allen:
http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
http://brockallen.com/2014/01/09/a-primer-on-external-login-providers-social-logins-with-owinkatana-authentication-middleware/
The fundemental idea is to register two authentication Middlewares. An active Cookie-Authentication and a passive OAuthBearer-Authentication. In Startup.Auth.cs they are added like this:
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/ExternalLogin/Login"),
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
});
You also add an ExternalLogin-Controller. Its Login-method has to redirect the user to the Login-page of your Authorization Server to get the authorization code. You have to supply a callback function where you will process the authorization code.
public async Task<ActionResult> Login(string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl) && Request.UrlReferrer != null)
returnUrl = Server.UrlEncode(Request.UrlReferrer.PathAndQuery);
if (Url.IsLocalUrl(returnUrl) && !string.IsNullOrEmpty(returnUrl))
_returnUrl = returnUrl;
//callback function
_redirectUrl = Url.Action("AuthorizationCodeCallback", "ExternalLogin", null, Request.Url.Scheme);
Dictionary<string, string> authorizeArgs = null;
authorizeArgs = new Dictionary<string, string>
{
{"client_id", "0123456789"}
,{"response_type", "code"}
,{"scope", "read"}
,{"redirect_uri", _redirectUrl}
// optional: state
};
var content = new FormUrlEncodedContent(authorizeArgs);
var contentAsString = await content.ReadAsStringAsync();
return Redirect("http://localhost:64426/oauth/authorize?" + contentAsString);
}
In your callback-function you exchange the authorization code for an access token (plus refresh token) challenge your passive OAuthBearer-authentication Middleware and signin with the Access token as your Cookie.
public async Task<ActionResult> AuthorizationCodeCallback()
{
// received authorization code from authorization server
string[] codes = Request.Params.GetValues("code");
var authorizationCode = "";
if (codes.Length > 0)
authorizationCode = codes[0];
// exchange authorization code at authorization server for an access and refresh token
Dictionary<string, string> post = null;
post = new Dictionary<string, string>
{
{"client_id", "0123456789"}
,{"client_secret", "ClientSecret"}
,{"grant_type", "authorization_code"}
,{"code", authorizationCode}
,{"redirect_uri", _redirectUrl}
};
var client = new HttpClient();
var postContent = new FormUrlEncodedContent(post);
var response = await client.PostAsync("http://localhost:64426/token", postContent);
var content = await response.Content.ReadAsStringAsync();
// received tokens from authorization server
var json = JObject.Parse(content);
_accessToken = json["access_token"].ToString();
_authorizationScheme = json["token_type"].ToString();
_expiresIn = json["expires_in"].ToString();
if (json["refresh_token"] != null)
_refreshToken = json["refresh_token"].ToString();
//SignIn with Token, SignOut and create new identity for SignIn
Request.Headers.Add("Authorization", _authorizationScheme + " " + _accessToken);
var ctx = Request.GetOwinContext();
var authenticateResult = await ctx.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ExternalBearer);
ctx.Authentication.SignOut(DefaultAuthenticationTypes.ExternalBearer);
var applicationCookieIdentity = new ClaimsIdentity(authenticateResult.Identity.Claims, DefaultAuthenticationTypes.ApplicationCookie);
ctx.Authentication.SignIn(applicationCookieIdentity);
var ctxUser = ctx.Authentication.User;
var user = Request.RequestContext.HttpContext.User;
//redirect back to the view which required authentication
string decodedUrl = "";
if (!string.IsNullOrEmpty(_returnUrl))
decodedUrl = Server.UrlDecode(_returnUrl);
if (Url.IsLocalUrl(decodedUrl))
return Redirect(decodedUrl);
else
return RedirectToAction("Index", "Home");
}
I hope this is useful for someone who is implementing the OAuth authorization code flow in his MVC 5 application.
I used official sample MVC Implicit Client which I believe is the correct authentication flow for MVC application.
For authorization I used this getting started, especially the part about infinite loop when roles are specified [Authorize(Roles = "Foo,Bar")] and user is authenticated but doesn't own any of these.

Resources