Comments (6)
@ossentoo I am quite confuse about your problem. Are you trying to use this B2C sample code, on an Azure AD (not B2C) scenario?
from active-directory-b2c-dotnetcore-webapp.
no - i am using Azure B2C. Anyway, I managed to resolve this, so I'm going to close the issue.
I think i may have had a bug in my own code elsewhere which caused the claims to be send correctly to this callback
from active-directory-b2c-dotnetcore-webapp.
@ossentoo my apologies to disturb you, I know this post was last year. My i ask how do you manage to solve this issue? Coz right now im having the same issue thank you.
from active-directory-b2c-dotnetcore-webapp.
hi @fad16papa. I had to work around the issue in the end. We ended up writing some functionality to request the user details we needed from b2c. We have an access token, and so can use this to query Microsoft Graph for the details we need. Clunky but it works.
from active-directory-b2c-dotnetcore-webapp.
@ossentoo
Maybe you can try this code
public static class ApplicationBuilderExtension
{
public static void UseEasyAuth2(this IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
// Create a user on current thread from provided header
if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID"))
{
// Read headers from Azure
var azureAppServicePrincipalIdHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0];
var azureAppServicePrincipalNameHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0];
var cookieContainer = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler()
{
CookieContainer = cookieContainer
};
string uriString = $"{context.Request.Scheme}://{context.Request.Host}";
foreach (var c in context.Request.Cookies)
{
cookieContainer.Add(new Uri(uriString), new Cookie(c.Key, c.Value));
}
string jsonResult;
using (HttpClient client = new HttpClient(handler))
{
var res = await client.GetAsync($"{uriString}/.auth/me");
jsonResult = await res.Content.ReadAsStringAsync();
}
//parse json
var obj = JArray.Parse(jsonResult);
string user_id = obj[0]["user_id"].Value<string>(); //user_id
// Create claims id
List<Claim> claims = new List<Claim>();
foreach (var claim in obj[0]["user_claims"])
{
claims.Add(new Claim(claim["typ"].ToString(), claim["val"].ToString()));
}
// Set user in current context as claims principal
var identity = new GenericIdentity(azureAppServicePrincipalIdHeader);
identity.AddClaims(claims);
// Set current thread user to identity
context.User = new GenericPrincipal(identity, null);
}
await next.Invoke();
});
}
}
use it in startup.cs,
app.UseEasyAuth2();
from active-directory-b2c-dotnetcore-webapp.
Hi @ossentoo thanks for the code and effort to help highly appreciated. I was able to solve my issue by adding a [Authorize(Roles = ("sample role"))] in every endpoint call of my API method were the roles is set via identity roles and stored it in JWT . Here is my sample code
[Authorize(Roles = ("sample role"))]
[HttpPost, Route("external/api/SubmitVehicleNumberTNPermitLand/{cassToken}")]
public async Task SubmitVehicleNumberTNPermitLand(string cassToken, [FromBody] VehiclePermitInformation vehiclePermitInformation)
{
//Instantiate the CassResponseModel
CassResponseModel cassResponseModel = new CassResponseModel();
//Instatiate the CassLogs
CassLogs cassLogs = new CassLogs();
string response = string.Empty;
try
{
//Instantiate VehicleInformationRSS and populate its properties
VehicleInformationRSS vehicleInformationRSS = new VehicleInformationRSS();
vehicleInformationRSS.requestType = "VHCINF";
vehicleInformationRSS.requestId = string.Format("{0}{1}", "VHCINF", Guid.NewGuid().ToString());
vehicleInformationRSS.requestDateTime = DateTime.Now;
vehicleInformationRSS.vehicleNo = vehiclePermitInformation.VehicleNumber; // get the vehicle number via permit table
vehicleInformationRSS.location = _configuration["Location:Checkpoint"]; // get the location set via app config
vehicleInformationRSS.permitCount = vehiclePermitInformation.PermitCount; // The total count of the permits inside per send request to CASS URI
foreach (var item in vehiclePermitInformation.PermitNumber)
{
vehicleInformationRSS.permitNo.Add(item);
}
#region Call the CASS Interface Endpoint
//use the TMSapi httpClient
var client = _clientUser.CreateClient("CASS");
//Retrieve the JWT toke in cookie and place it inside the header request
//var token = Request.Cookies["Authorization"];
client.DefaultRequestHeaders.Add("Authorization", cassToken);
//Call the CASS URI and pass the jsonObject as POST method
var putTask = client.PostAsJsonAsync<VehicleInformationRSS>("sample/sample", vehicleInformationRSS).Result;
#endregion
#region Check the response of cass interface
cassResponseModel = putTask.Content.ReadAsAsync<CassResponseModel>().Result;
response = cassResponseModel.ReasonCode;
//Counter Check tries
int errorChecker = 0;
int counterCheck = Convert.ToInt32(_configuration["CASSUri:counterCheck"]);
//Check if the request == 002
if (response == null)
{
for (errorChecker = 0; errorChecker <= counterCheck; errorChecker++)
{
//Call again the CASS URI
putTask = client.PostAsJsonAsync<VehicleInformationRSS>("land/permits/", vehicleInformationRSS).Result;
//Check if the putask is still == null
if (putTask != null)
{
return Ok();
break;
}
if (errorChecker == counterCheck)
{
return BadRequest("Cannot Connect to the CASS Interface");
break;
}
}
}
//Check if the request == 002
if (response.Equals("002"))
{
return BadRequest("Invalid Permit Number");
}
//Check if the request = 001
if (response.Equals("001"))
{
return BadRequest("Invalid Vehicle Number");
}
return Ok("Process Successfull");
#endregion
}
catch (Exception ex)
{
// Logging the error
_logger.LogError($"Error while RSS call the CASS post request method SubmitVehicleNumberTNPermit. Exception: {ex.Message}");
// Returning badRequest
return BadRequest("Error while execute the SubmitVehicleNumberTNPermitLand");
}
}
from active-directory-b2c-dotnetcore-webapp.
Related Issues (20)
- got secure error when I try to sign in HOT 2
- Not compatible with aspnet core 2.1 HOT 1
- Error from RemoteAuthentication: Message contains error: 'redirect_uri_mismatch', error_description: 'AADB2C90006: The redirect URI 'http://b2.95e4700435c54427a457.northeurope.aksapp.io/signin-oidc' provided in the request is not registered for the client id 'eb201049-e7b1-4227-9a7c-5bb259261d37'. Correlation ID: 8f75359e-009f-44e3-b537-3f85f58cdd9c HOT 6
- ERROR Account username: Missing from the token response environment login.microsoftonline.com home account id: AccountId: XXXX HOT 8
- Single-Sign Out AD B2C HOT 2
- NullReferenceException in MSALSessionCache constructor HOT 1
- acquireTokenSilent sometimes returns a null accesstoken HOT 1
- Error messages in OnRemoteFailure should be url encoded before appending to query string HOT 3
- Latest version of AAD B2C? HOT 2
- Update the repository to not use Bower HOT 3
- Update the repository to use the latest MSAL version HOT 2
- b2clogin.com for ASP.NET Core HOT 7
- No accounts being returned on cca.GetAccountsAsync()
- Words 'simple' and 'dead simple' should be removed from content. HOT 1
- Unit testing for SessionController HOT 1
- Compatibility with .NET Core 3.1 HOT 2
- How do I diagnose errors? HOT 1
- How to pass domain_hint while calling B2C for login HOT 1
- How to select a policy at runtime?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from active-directory-b2c-dotnetcore-webapp.