.Net Core Web API Bearer The issuer is invalid - jwt

I have written a Blazor WASM app based on the latest Microsoft template. In development mode it all works great but after publishing it to Azure App Service I randomly get a 401 unauthorised when calling the API, looking at the returned headers I get
WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://*domain*.azurewebsites.net' is invalid"
This is when the client is using the https://domain.azurewebsites.net client. So it matches the web API.
I also have a custom domain attached to the app service, this means there is also https://www.domain.co.uk and https://domain.co.uk both are SSL'd.
I have checked the JWT token and it contains the correct URL for the version of the website I am calling.
Sometimes everything works but 60% of the time it allows the user to login and then fails on the API calls. I can't seem to track it to 1 domain name or pattern like expired logins. If you log out and then log back in, it doesn't clear the issue.
The configure looks like this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
endpoints.MapFallbackToFile("index.html");
});
}
Any help or hints in the right direction is appreciated
Cheers
Dave

In my case it was caused by Linux environment of App Service. Now documentation has a clear note on that:
For Azure App Service deployments on Linux, specify the issuer explicitly in Startup.ConfigureServices.
This is how I set it:
services.Configure<JwtBearerOptions>(
IdentityServerJwtConstants.IdentityServerJwtBearerScheme,
options =>
{
options.Authority = "https://my-site.azurewebsites.net";
#if DEBUG
options.Authority = "https://localhost:5001";
#endif
});

Related

Keycloak.js can not get access token when login with Google and Facebook

I'm build a system for our company using Keycloak. I use keycloak.js for by-pass default login page of Keycloak.
function myFunction() {
let kcLogin = keycloak.login;
keycloak.login = (options) => {
options.idpHint = 'facebook';
kcLogin(options).then(auth => {
alert("keycloak Login");
if(auth) {
alert("token" + kc.token);
} else {
alert("auth is null");
}
});
};
keycloak.init({ onLoad: 'login-required' }).then(function(authenticated) {
alert(authenticated ? 'authenticated' : 'not authenticated');
}).catch(function() {
alert('failed to initialize');
});
}
But I can NOT get access token / refresh token after login.
I check: keycloak.token = undefined.
Please help me!
PS: I always get exception of keycloak.init then redirect to facebook login ( or google login )
alert('failed to initialize');
Thank you so much.
Code here: https://github.com/loizenai/SpringBoot-Keycloak-Social-Authentication-Py-Pass-Default-Login/tree/main/SpringBootKeyCloakSocialSignIn
You are trying to configure your backend and frontend with Keycloak.
Either you just have to configure your backend to integrate with your keycloak or Integration your frontend application and your backend will only verify the token.
The current application architecture you are following is an MVC pattern.
Where your spring boot(backend) application controls the integration with Keycloak.
Please refer to this article: Secure spring boot 2 using Keycloak
What you are trying to target follows this kind of architecture pattern:
Secure Vue.js apps with Keycloak | DevNation Tech Talk
In the above reference, I have used the Vue application but you can use your vanilla html/js application as well to integrate with keycloak.
First, try keycloak login flow in your application and then you can enable social login.

ASP.NET Core with windows auth always gives 403

Using Visual Studio 2019 I created a .NET Core API, and I told it to use windows authentication. I then edited the WeatherForecastController.cs file and added a simple post route:
[HttpPost]
public ActionResult Foo()
{
return NoContent();
}
If I then run the app locally, via VS, and try to POST to that, passing NTLM credentials, it still gives a forbidden (403) error. I've seen multiple possible solutions to this from googling but nothing seems to work.
In my Startup.cs I have this
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
and in the ConfigureServices I added
services.AddAuthentication(IISDefaults.AuthenticationScheme);
Well, this had nothing to do with authentication. Postman was returning a 403 no matter what. I finally dropped down to doing it manually via curl and found the server was throwing an exception in a completely unrelated area. Fixing that fixed the issue.

How to get JWT token for current Liferay session

I have configured Liferay v7.3.4 CE to authenticate with AWS Cognito using OpenID Connect Provider, and that all works fine.
I would now like to invoke REST APIs in AWS, from within Liferay, using the JWT token obtained from Cognito during the sign-in process.
It would seem this JWT token should be available within Liferay, correct? If so, a source code example demonstrating how to access this would be very much appreciated.
This token would then be added to the Authorization header of API calls to an instance of the AWS API Gateway secured by the same Cognito instance from which the user has just signed in. But first things first... how would someone programmatically access the JWT token for the current Liferay session?
Hope this makes sense.
I've got this working.
First, I am using Maven (not gradle) to build Liferay projects. To this end, I've added the following to my portlet's pom.xml file:
<dependency>
<groupId>com.liferay</groupId>
<artifactId>com.liferay.portal.security.sso.openid.connect.api</artifactId>
<scope>provided</scope>
</dependency>
Next, in my portlet's render method, I've added the following code:
public void render(RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException
{
try {
// get the jwtToken from the renderRequest parameter
String jwtToken = null;
HttpSession session = PortalUtil.getOriginalServletRequest(PortalUtil.getHttpServletRequest(renderRequest)).getSession();
if (session.getAttribute(OpenIdConnectWebKeys.OPEN_ID_CONNECT_SESSION) instanceof OpenIdConnectSession) {
OpenIdConnectSession openIdConnectSession = (OpenIdConnectSession) session.getAttribute(OpenIdConnectWebKeys.OPEN_ID_CONNECT_SESSION);
jwtToken = openIdConnectSession.getAccessTokenValue();
}
// call a REST API with the jwt token
List<Organization> organizations = masterDataClient.fetchOrganizations(jwtToken);
// do other stuff
super.render(renderRequest, renderResponse);
} catch (Exception e) {
throw new PortletException(e);
}
}

How to add policy to Keycloak - UI crashes

I'm trying to enable flow when some admin user by some admin client is able to create users and obtain their access tokens to be used for another clients.
I have KeyCloak setup with token exchange and fine grained authz enabled and configured clients. I'm able to login my admin user by REST api, then exchange token. But when I specify audience I got error.
This one returns token but I need token for another client/audience.
http -f POST https://my-keycloak-server.com/auth/admin/realms/my-realm/protocol/openid-connect/token grant_type=urn:ietf:params:oauth:grant-type:token-exchange requested_subject=1a147915-53fe-454d-906a-186fecfa6974 client_id=api-admin client_secret=23a4ecbe-a9e8-448c-b36a-a45fa1082e6e subject_token=eyJhbGeiOiJSUzI1NiIs......
This one is failing with error.
http -f POST https://my-keycloak-server.com/auth/admin/realms/my-realm/protocol/openid-connect/token grant_type=urn:ietf:params:oauth:grant-type:token-exchange requested_subject=1a147915-53fe-454d-906a-186fecfa6974 client_id=api-admin client_secret=23a4ecbe-a9e8-448c-b36a-a45fa1082e6e subject_token=eyJhbGeiOiJSUzI1NiIs...... audience=my-another-client
{
"error": "access_denied",
"error_description": "Client not allowed to exchange"
}
So I tried to setup fine grained auth for target audience client (enabled it in tab, then tried to add policy for my admin user to be able to exchange token) but when I want to add policy that will allow my admin user to perform token exchange I'm stuck on UI error.
When typing policy name I got 404 when Keycloak is looking for name colisions. Afaik 404 in this case shouldn't block form from posting because it is no name collision. Instead I got instantly redirected with error.
https://my-keycloak-server.com/auth/admin/realms/my-realm/clients/1bafa9a4-f7e2-422c-9188-58ea95db32ef/authz/resource-server/policy/search?name=some-name
In the end of the day I can't add any policy in Keycloak. All the time form validation is ending up with crash caused by 404 policy name not found.
I'm using dockerized keycloak 10.0.0
Any ideas?
I hacked it by live editing Angular JS UI script function that performs verification in line 2403.
this.checkNameAvailability = function (onSuccess) {
if (!$scope.policy.name || $scope.policy.name.trim().length == 0) {
return;
}
ResourceServerPolicy.search({
realm: $route.current.params.realm,
client: client.id,
name: $scope.policy.name
}, function(data) {
if (data && data.id && data.id != $scope.policy.id) {
Notifications.error("Name already in use by another policy or permission, please choose another one.");
} else {
onSuccess();
}
});
}
to
this.checkNameAvailability = function (onSuccess) {
onSuccess();
}
And that end up with successfuly added policy. Still looks like it's UI bug.

CSRF Token not updated properly (Ionic + Spring Security)

I'm developing an app using Ionic Framework and generated a JHipster project for my backend. My JHipster project runs on an extra Server and is called via REST requests from my App. So my problem now is handling the CORS and CSRF configuration.
My JHipster project has its own frontend, which runs on the same domain and while testing I can reach my backend without any issues. However, when I want to call my backend on the server from my Ionic app my xsrf tokens wont update properly and, therefore, I cannot access my backend. I already tried several solutions from different stack overflow posts, but none of them worked for me.
For example:
Ionic using CORS and CSRF
Could not verify token
https://github.com/angular/angular/issues/18859
What I've done so far:
I enabled csrf in my SecurityConfiguration in my JHipster project
http
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
added CORS configuration
cors:
allowed-origins: 'http://localhost:8100, ionic://localhost, http://localhost'
allowed-methods: 'POST, GET, OPTIONS, DELETE, PUT, HEAD'
allowed-headers: 'Origin, X-Requested-With, Content-Type, Accept, x-auth-token, Authorization, X-CSRF-Token, x-xsrf-token, XSRF-TOKEN'
exposed-headers: 'Authorization,Link,X-Total-Count,XSRF-TOKEN, X-XSRF-TOKEN'
allow-credentials: true
max-age: 86400
wrote an interceptor
#Injectable()
export class HttpXSRFInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor, private csrfService:CSRFService, private $sessionStorage: SessionStorageService) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const headerName = 'XSRF-TOKEN';
const respHeaderName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({ headers: req.headers.set(respHeaderName, token) });
req.clone({
withCredentials: true
});
}
return next.handle(req);
}
}
added HttpClientXsrfModule in my app.module.ts and the interceptor
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-XSRF-TOKEN',
}),
{
provide: HTTP_INTERCEPTORS,
useClass: HttpXSRFInterceptor,
multi: true
},
My Problem:
I dont get a xsrf token when starting my App in the browser, but after I send a post request the token gets set as a cookie.
For example when logging in, the first attempt fails due to the missing token, but the second login request is successful because now the response header for the xsrf token is not null anymore. Furthermore, the token does not update itself even though the server response has a new token in its header.
From my understanding
the first time I get my token should be immediately after loading the start page of my app
the token should be updated after each response from the server (backend) and the updated token is used for the next request
Therefore my problem is that both these issues do not happen and I don't know how to fix it.
I appreciate any help!
cheers
I'm the author of Ionic for JHipster so hopefully, I can help you with this.
First of all, CSRF shouldn't be an issue unless you're running your apps on the same port. In my experience, when you run them on separate ports, your client can't read the cookie. As for CORS, that's not a problem for me when running locally. I believe it's because the CORS settings for the dev profile are wide open. Can you try using the settings from the dev profile in your prod profile and see if it helps?
For reference, they are:
jhipster:
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800
If this works, I'd try changing your allowed origins to an array, or just use one. http://localhost:8100 should be all you need if running locally.