Flutter web call to .net core api error 'Access-Control-Allow-Origin' - flutter

Flutter web call to .net core api error 'Access-Control-Allow-Origin'
Help me i want flutter-Web call api
i use .net core api
how to allow 'Access-Control-Allow-Origin' on .net core api
code in Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace test_api
{
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
// app.UseResponseCaching();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
Flutter Web error

The error means that your api (this unrelated to flutter) has blocked the request due to CORS policy. CORS blocks request from other IP. So you pretty much have to enable it.
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Follow the guidelines and the answers here. Try to search for your specific asp.net core version. Furhtermore the EnableCors attribute on top of the controllers is required for this to work. Your allow only specific origins simply does not specify any kind of hosts. It specifies only the name of the policy and also you havent used in the services

Related

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.

.Net Core Web API Bearer The issuer is invalid

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
});

Spring boot admin shows status of gateway server down

I develop a micro services environment.It is developed by the spring cloud.
The gateway server has been developed by the Zuul and has secured by X.509 certificate authentication(mutual authentication).
I use spring boot admin for monitoring the micro services.
I already use Spring Cloud Discovery for my applications and i added a DiscoveryClient to Spring Boot Admin Server:
#Configuration
#EnableAutoConfiguration
#EnableDiscoveryClient
#EnableAdminServer
public class ApiAdminServerApplication {
public static void main(String[] args) {
SpringApplication.run(ApiAdminServerApplication.class, args);
}
}
Spring boot admin properties:
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=ALWAYS
spring.security.user.name=admin
spring.security.user.password=password
Service discovery properties:
management.endpoint.metrics.enabled=true
management.endpoints.web.exposure.include=*
management.endpoint.prometheus.enabled=true
management.metrics.export.prometheus.enabled=true
management.metrics.tags.application=${spring.application.name}
Gateway properties:
server.ssl.enabled=true
server.ssl.key-store-type=PKCS12
server.ssl.key-store=classpath:tls/keyStore.p12
server.ssl.key-store-password=changeit
server.ssl.trust-store=classpath:tls/trustStore.jks
server.ssl.trust-store-password=changeit
server.ssl.trust-store-type=JKS
server.ssl.client-auth=need
The gateway server is shown in spring boot admin panel as an application but its status is down.
How do I config spring boot admin for monitoring https gateway application?
Spring Boot Admin makes a call to /actuator/health endpoint to know the application health. Please check if this endpoint is working fine, otherwise, you might need to configure it based on your requirements.
By default Spring check for a number of health indicators mentioned here:
https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-features.html#auto-configured-healthindicators
You can configure your own indicator as well, a snippet from documentation:
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
#Component
public class MyHealthIndicator implements HealthIndicator {
#Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
}
I disable SSL authentication in the application.properties file of gateway :
management.server.ssl.enabled=false
And ignore actuator url path in the WebSecurityConfigurerAdapter class of gateway:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers( "/actuator/health/**").permitAll()
.anyRequest().authenticated().and()
.x509()
.subjectPrincipalRegex("CN=(.*?)(?:,|$)")
.userDetailsService(userDetailsService());
}
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/actuator/**");
}
But be careful , this solution expose important health info of the gateway server for all request.

Custom Authentication - Spring boot 403 forbidden error

I was trying it implement custom authentication, Authentication works fine, but have problems with Authorization. I am using JWT tokens, Any API I try to access it throwing me a 403 forbidden error. I am not sure what is wrong. I have the full source code in github. https://github.com/vivdso/SpringAuthentication, Spring boot magic is not working on this. Any pointers are apperciated.
Using MongoDb as my repository to store user accounts and roles.
InMemory Authentication is working fine, but Custom Authentication always returs 403, Below is my I extended WebSecurityConfigurerAdapter
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
// authenticationManagerBuilder.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
// authenticationManagerBuilder.inMemoryAuthentication().withUser("user").password("user").roles("USER");
authenticationManagerBuilder.authenticationProvider(getCustomAuthenticationProvider());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/customer").hasAuthority("ADMIN")
.antMatchers(HttpMethod.GET, "/order").hasAuthority("USER").and()
.csrf().disable();
}
#Bean
protected CustomAuthenticationProvider getCustomAuthenticationProvider(){
return new CustomAuthenticationProvider();
}
I don't have any custom implementation for authorization.
The issue is resolved, I have updated Github repository. The spring boot security was working fine, the issue was the roles assigned to the user collection was a Json string object (e.g. {"role":"ROLE_ADMIN"}) instead of sting object "ROLE_ADMIN".
Thanks

How to avoid custome filter to run for non-secured urls in spring-security

I am building a REST based web application and i have applied the spring security to it successfully but my concern is that i have added a custom filter
http
.authorizeRequests()
.antMatchers("/mypro/userCont/signup").permitAll()
.and()
.addFilterBefore(new CustomFilter(), UsernamePasswordAuthenticationFilter.class)
.httpBasic();
i want that this filter should only run for secured urls not for unsecured urls if it get runs for non secured url then it should not interrupt me to get resource on non-secure url.
My scenerio is if user is not logged in for secured url custom filter should be run which check the Principal using below code:
Authentication auth = (Authentication) SecurityContextHolder.getContext().getAuthentication();
if the auth is null user should seen default spring security login popup
and if i hit the non secure url i should get to the resource.
Can anyone help me.
You can skip security entirely for particular resources by configuring WebSecurity. In this case, Spring security will totally ignore that URL pattern:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity webSecurity) throws Exception
{
webSecurity
.ignoring()
.antMatchers("/resources/**"); //skip security entirely
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilter(mycustomFilter)
.authorizeRequests().anyRequest()
.and()
.httpBasic();
}
}
or, you can just simply use the permitAll() method to exclude the ones you need to allow anonymous access.
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilter(mycustomFilter)
.authorizeRequests()
.antMatchers("/not-secured/**").permitAll()
.and()
.httpBasic();
}
}