XMLHttpRequest at xxx from origin xxx has been blocked by CORS: No 'Access-Control-Allow-Origin' header - spring-boot

hi I am working on spring boot, angular 8, and mongodb. I am facing the error
Access to XMLHttpRequest at 'http://localhost:8080/employee/activeemployeesummary' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
when i test same code on postman it work perfectly fine, however it don't work angular, and because chrome using the CORS policy.
My code:
package com.sani.springbootrestfulapi;
public class SpringBootMongoApplication extends SpringBootServletInitializer {
public static void main(String args[]) {
SpringApplication.run(SpringBootMongoApplication.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH")
.allowedHeaders("Origin, X-Requested-With, Content-Type, Accept")
.allowedOrigins("http://localhost:4200");
}
};
}
}
below: employee controller code
package com.sani.springbootrestfulapi.controller;
#RestController
#RequestMapping("employee")
public class EmployeeController {
#Autowired
private EmployeeService empService;
#Autowired
private OrganizationService organizationService;
#PostMapping("/save")
public ResponseEntity<EmployeeEntity> save(#RequestBody EmployeeEntity emp) {
if (empService.findByrNumber(emp.getrNumber()))
return new ResponseEntity<EmployeeEntity>(HttpStatus.FOUND);
else {
organizationService.joinOrganization(emp);
return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
}
}
#PutMapping("/update") /* here we need to pass id, the spring will consider as update */
public ResponseEntity<EmployeeEntity> update(#RequestBody EmployeeEntity emp) {
EmployeeEntity employee = empService.getOne(emp.getId());
if (employee != null) {
organizationService.joinOrganization(emp);
return new ResponseEntity<EmployeeEntity>(HttpStatus.OK);
} else
return new ResponseEntity<EmployeeEntity>(HttpStatus.NOT_FOUND);
}
#GetMapping("/activeemployeesummary")
public List<EmployeeEntity> getActiveEmployeeSummary() {
List<EmployeeEntity> employee = new ArrayList<>();
empService.getActiveEmployeeSummary().forEach(employee::add);
return employee;
}
#GetMapping("/inactiveemployeesummary")
public List<EmployeeEntity> getInactiveEmplo`enter code here`yeeSummary() {
List<EmployeeEntity> employee = new ArrayList<>();
empService.getInactiveEmployeeSummary().forEach(employee:`enter code here`:add);
return employee;
}
}

Add this #Bean in your #Configuration or your main class.
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(
Arrays.asList("GET","POST","HEAD","DELETE","PUT","OPTIONS"));
configuration.setMaxAge(1l);
configuration.setAllowCredentials(true);
configuration.setAllowedHeaders(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}

I think you just missed that header =>
Access-Control-Allow-Origin: *

Related

Keycloak Multitenancy static Content Return 404

I'm working on modernizing monolithic application to be microservice based application supporting multi tenancy using Spring boot, Keycloak 17, the configuration is Keycloak configuration file depending on the path referring to this example
For me it it working, and can load the deployments from json, login, below is the url for the application and I'm parsing branch1 after "tenant" without issues
http://localhost:8100/tenant/branch1/
The main issue is rendering css and JS files which is containing tenant name knwoing that I'm using sing WAR
with multiple realms
http://localhost:8100/tenant/branch1/resources/bootstrap/js/bootstrap.min.js --> return 404 which is not exist
Actual code for including static contents
in The jsp files I'm reading css/js files as before <link rel="stylesheet" href="resources/bootstrap/css/bootstrap.min.css">
keycloal json file example
{"realm": "branch1",
"auth-server-url": "http://localhost:8181/",
"ssl-required": "external",
"resource": "app",
"public-client": true,
"confidential-port": 0,
"principal-attribute": "preferred_username"}
Please advise
rendering static content
is there any guidance after authentication to return one URL without tenant/branch1 specially I'm using CurrentTenantIdentifierResolver inside my application
#ConditionalOnProperty(prefix = "keycloak.config", name = "resolver", havingValue = "path")
public class PathBasedConfigResolver implements KeycloakConfigResolver {
private final ConcurrentHashMap<String, KeycloakDeployment> cache = new ConcurrentHashMap<>();
#SuppressWarnings("unused")
private static AdapterConfig adapterConfig;
#Override
public KeycloakDeployment resolve(OIDCHttpFacade.Request request) {
System.out.println("inside resolve :: ");
String realm = SubdomainUtils.obtainTenantFromSubdomain(request.getURI());
if (realm.contains("?")) {
realm = realm.split("\\?")[0];
}
if (!cache.containsKey(realm)) {
InputStream is = this.getClass().getResourceAsStream("/" + realm + "-keycloak.json");
cache.put(realm, KeycloakDeploymentBuilder.build(is));
}
return cache.get(realm);
}
static void setAdapterConfig(AdapterConfig adapterConfig) {
PathBasedConfigResolver.adapterConfig = adapterConfig;
}
}
public class SpringKeycloakSecurityConfiguration {
#DependsOn("keycloakConfigResolver")
#KeycloakConfiguration
#ConditionalOnProperty(name = "keycloak.enabled", havingValue = "true", matchIfMissing = true)
public static class KeycloakConfigurationAdapter extends KeycloakWebSecurityConfigurerAdapter {
/**
* Registers the KeycloakAuthenticationProvider with the authentication manager.
*/
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
SimpleAuthorityMapper soa = new SimpleAuthorityMapper();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(soa);
auth.authenticationProvider(keycloakAuthenticationProvider);
}
/**
* Defines the session authentication strategy.
*/
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
// required for bearer-only applications.
// return new NullAuthenticatedSessionStrategy();
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
#Override
protected AuthenticationEntryPoint authenticationEntryPoint() throws Exception {
return new MultitenantKeycloakAuthenticationEntryPoint(adapterDeploymentContext());
}
#Override
protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
KeycloakAuthenticationProcessingFilter filter = new KeycloakAuthenticationProcessingFilter(
authenticationManager(), new AntPathRequestMatcher("/tenant/*/sso/login"));
filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
return filter;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakAuthenticationProcessingFilterRegistrationBean(
KeycloakAuthenticationProcessingFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakPreAuthActionsFilterRegistrationBean(
KeycloakPreAuthActionsFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakAuthenticatedActionsFilterBean(
KeycloakAuthenticatedActionsFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#SuppressWarnings({ "rawtypes", "unchecked" })
#Bean
public FilterRegistrationBean keycloakSecurityContextRequestFilterBean(
KeycloakSecurityContextRequestFilter filter) {
FilterRegistrationBean registrationBean = new FilterRegistrationBean(filter);
registrationBean.setEnabled(false);
return registrationBean;
}
#Bean
#Override
#ConditionalOnMissingBean(HttpSessionManager.class)
protected HttpSessionManager httpSessionManager() {
return new HttpSessionManager();
}
/**
* Configuration spécifique à keycloak (ajouts de filtres, etc)
*
* #param http
* #throws Exception
*/
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
// use previously declared bean
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
// keycloak filters for securisation
.and().addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), X509AuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and().logout().addLogoutHandler(keycloakLogoutHandler()).logoutUrl("/tenant/*/logout")
.logoutSuccessHandler(
// logout handler for API
(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) -> response.setStatus(HttpServletResponse.SC_OK))
.and().authorizeRequests().antMatchers("mobileservlet/**").permitAll().antMatchers("**/favicon.ico")
.permitAll().antMatchers("/error").permitAll().antMatchers("/login.go").permitAll()
.antMatchers("/resources/*").permitAll().anyRequest().authenticated();
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList(HttpMethod.OPTIONS.name(), "GET", "POST"));
configuration.setAllowedHeaders(
Arrays.asList("Access-Control-Allow-Headers", "Access-Control-Allow-Origin", "Authorization"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
}
public class MultitenantKeycloakAuthenticationEntryPoint extends KeycloakAuthenticationEntryPoint {
public MultitenantKeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext) {
super(adapterDeploymentContext);
}
public MultitenantKeycloakAuthenticationEntryPoint(AdapterDeploymentContext adapterDeploymentContext, RequestMatcher apiRequestMatcher) {
super(adapterDeploymentContext, apiRequestMatcher);
}
#Override
protected void commenceLoginRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("inside commenceLoginRedirect :: ");
String path = request.getRequestURI();
int multitenantIndex = path.indexOf("tenant/");
if (multitenantIndex == -1) {
throw new IllegalStateException("Not able to resolve the realm from the request path!");
}
String realm = path.substring(path.indexOf("tenant/")).split("/")[1];
if (realm.contains("?")) {
realm = realm.split("\\?")[0];
}
String contextAwareLoginUri = request.getContextPath() + "/tenant/" + realm + DEFAULT_LOGIN_URI;
response.sendRedirect(contextAwareLoginUri);
}
}
Bad news, the Keycloak adapters for spring you are using are very deprecated. Don't use it.
Better news, I host spring-boot starters for resource-servers which support multi-tenancy: accept identities issued by more than just one issuer (as many realms as you need in your case) and retrieve "roles" from realms and clients with the mapping you want (control case and prefix). It also enables you to configure "public" routes and CORS configuration from preperties file (plus a few more things).
Configuration for realm1 and other-realm both used by two clients (some client and other-client) is as simple as:
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<!-- replace "webflux" with "webmvc" if your app is a servlet -->
<!-- replace "jwt" with "introspecting" to use token introspection instead of JWT decoding -->
<artifactId>spring-addons-webflux-jwt-resource-server</artifactId>
<!-- this version is to be used with spring-boot 3.0.0-RC2, use 5.x for spring-boot 2.6.x or before -->
<version>6.0.5</version>
</dependency>
#EnableMethodSecurity
public static class WebSecurityConfig { }
com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm1
com.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles
com.c4-soft.springaddons.security.issuers[1].location=https://localhost:8443/realms/other-realm
com.c4-soft.springaddons.security.issuers[1].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles
com.c4-soft.springaddons.security.cors[0].path=/some-api

How to fix Cors error Access-Control-Allow-Origin missing

I have a spring boot rest application and I am not using Spring security. My rest service looks like this
#RestController
#CrossOrigin
public class AuthenticationService {
...
#GetMapping(path = "/getUser")
public JSONObject getUser() {
...
}
}
I call the API from a REST application using axios get. Everything works fine locally.
But when the application is deployed on cloud as a docker image, I get the 403 error
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Even when I add a CorsConfiguration file I get the same error.
#Configuration
public class CorsConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer()
{
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*")
.allowedHeaders("Accept", "Origin", "X-Requested-With,Content-Type", "Authorization", "X-XSRF-Header")
.allowCredentials(true);
}
};
}
}
I have spent a lot of time to find a solution for this but somehow it isn't working.
Declaring a bean works fine for me:
#Configuration
public class WebConfigurer implements ServletContextInitializer, WebMvcConfigurer {
private final Environment env;
private final MyProperties properties;
public WebConfigurer(Environment env, MyProperties properties) {
this.env = env;
this.properties = properties;
}
#Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = properties.getCors();
if (config.getAllowedOrigins() != null && !config.getAllowedOrigins().isEmpty()) {
log.debug("Registering CORS filter");
source.registerCorsConfiguration("/api/**", config);
source.registerCorsConfiguration("/management/**", config);
source.registerCorsConfiguration("/v3/api-docs", config);
}
return new CorsFilter(source);
}
}
Yaml properties:
# CORS is only enabled by default with the "dev" profile
cors:
allowed-origins: '*'
allowed-methods: '*'
allowed-headers: '*'
exposed-headers: 'Authorization,Link,X-Total-Count'
allow-credentials: true
max-age: 1800
fixed by adding spring security

Access-Control-Allow-Origin error with DELETE, while working fine with GET / POST

BackEnd is Spring, I'v configured CORS like this
#SpringBootApplication
public class App {
public static void main(String args[]){
SpringApplication.run(App.class, args);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
Now I got following code in Controller
#PostMapping("/add")
public ProductDto addProduct(#Valid #RequestBody ProductDto productDto){
return productService.addProduct(productDto);
}
#RequestMapping(path="/remove/{id}", method=RequestMethod.DELETE)
#ResponseBody
public String removeProduct(#PathVariable Long id) {
return productService.removeProduct(id);
}
And from Angular 6 FrontEnd I'm calling those 2 endpoints
let httpHeaders = new HttpHeaders({
'Content-Type' : 'application/json',
});
let options = {
headers: httpHeaders
};
addProduct() {
const product = new Product();
product.name = this.productNameValue;
product.categoryName = this.categoryValue;
product.kcal = this.caloriesValue;
product.protein = this.proteinValue;
product.fat = this.fatValue;
product.carb = this.carbsValue;
this.http.post('http://localhost:8080/product/add', JSON.stringify(product), options).subscribe(data => this.populateProductTable());
}
removeProduct(x: any) {
const url = 'http://localhost:8080/product/remove/' + x.id;
this.http.delete(url, options).subscribe(data => console.log(data));
}
First one (and similar GET method) works fine, when I try to use DELETE, I got
Failed to load http://localhost:8080/product/remove/2: Response to
preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
You need to add DELETE http-verb
For Spring Web MVC
#Configuration
#EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
}
For Spring Boot:
#Configuration
public class MyConfiguration {
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
}
};
}
}
To know how CORS works with spring, refer:
https://spring.io/blog/2015/06/08/cors-support-in-spring-framework#javaconfig
Spring security CORS Filter

Swagger doesn't display information about methods - SpringBoot

I have an API in Java SpringBoot and I want to document it in Swagger.
I have done the following (I only include classes that contain some code related to Swagger):
Main class
#EnableSwagger2
public class ProvisioningApiApplication {
public static void main(String[] args) {
if (AuthConfigFactory.getFactory() == null) {
AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());
}
SpringApplication.run(ProvisioningApiApplication.class, args);
}
#Bean
public Docket swaggerSpringMvcPluggin() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
#Component
#Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
enable(SerializationFeature.INDENT_OUTPUT);
}
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Provisioning API")
.version("0.0.1")
.build();
}
}
Controller
#RestController
#EnableAutoConfiguration
#CrossOrigin
public class RecursoController {
#Autowired
private Configuration configuration;
#Autowired
private TypeSpecService typeSpecService;
#Autowired
private IoTAgentService ioTAgentService;
#Autowired
private OrionService orionService;
#Autowired
private DeviceIdService deviceIdService;
#ApiOperation(value = "Put a device", nickname = "provisionDevice", tags = "Device")
#ApiResponses({
#ApiResponse(code = 200, message = "Ok", response = NewDeviceResponse.class)
})
#RequestMapping(method = RequestMethod.PUT, value = "/devices", consumes = "application/json", produces = "application/json")
public ResponseEntity<NewDeviceResponse> provisionDevice(#RequestBody NewDeviceRequest newDeviceRequest,
#RequestHeader("X-Auth-Token") String oAuthToken) {
// what my method does
}
The documentation results in the following swagger.json file:
{
swagger: "2.0",
info: {
version: "0.0.1",
title: "Provisioning API"
},
host: "localhost:8080",
basePath: "/"
}
As you can see, it only contains the name and the version of API but not the provisionDevice method.
I've tried everything but I can't figure it out what I'm doing bad. What am I missing?
Did you add #Api annotation in your class, where you have your main services?

Intercept the SSO cookie before the authorization server redirects the page

I have been banging my head for over a week to intercept the SSO cookie before the Authorization server redirects me my app page.
I'm implementing mitreid-connect for openid configuration. I have followed the documentation in the link and configured it using Java Config. Everything works fine, the redirects and etc., but I'm trying to implement AbstractPreAuthenticatedProcessingFilter to intercept the SSO cookie before the authorization server consumes it and generates the IdToken.
Please let me know if this is not right. I'm very new to spring-security and its scraping my scales off and its driving me crazy how to get hold to sso cookie
I have found this link
Please help me
#Configuration
public class filter extends AbstractPreAuthenticatedProcessingFilter {
#Bean(name = "singleSignOnFilter")
public String filter() {
return "PRE_AUTH_FILTER";
}
#Override
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
return null;
}
#Override
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
Cookie[] cookie = request.getCookies();
for(int i = 0; i < cookie.length; i++) {
System.out.println(cookie[i].getName() + " - " + cookie[i].getValue());
}
return null;
}
}
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Inject
private ClientDetailsEntity client;
#Inject
private String issuer;
#Bean
public ProviderManager providerManager() {
List<AuthenticationProvider> authenticationProvider = new LinkedList<AuthenticationProvider>();
authenticationProvider.add(oidcAuthProvider());
return new ProviderManager(authenticationProvider);
}
#Bean(name = "authenticationProvider")
public AuthenticationProvider oidcAuthProvider() {
return new OIDCAuthenticationProvider();
}
#Bean(name = "authoritiesMapper")
public OIDCAuthoritiesMapper authorityMapper() {
NamedAdminAuthoritiesMapper namedAdminAuthMapper = new NamedAdminAuthoritiesMapper();
namedAdminAuthMapper.setAdmins(admins());
return namedAdminAuthMapper;
}
#Bean(name = "admins")
public Set<SubjectIssuerGrantedAuthority> admins() {
Set<SubjectIssuerGrantedAuthority> admin = new HashSet<SubjectIssuerGrantedAuthority>();
return admin;
}
#Bean(name = "openIdConnectAuthenticationFilter")
public Filter openIdConnectAuthenticationFilter() {
OIDCAuthenticationFilter oidcAuthFilter = new OIDCAuthenticationFilter();
oidcAuthFilter.setAuthenticationManager(providerManager());
oidcAuthFilter.setIssuerService(issuerService());
oidcAuthFilter.setClientConfigurationService(clientConfigurationService());
oidcAuthFilter.setAuthRequestUrlBuilder(authRequestUrlBuilder());
return oidcAuthFilter;
}
#Bean(name = "issuerService")
public IssuerService issuerService() {
StaticSingleIssuerService issuerService = new StaticSingleIssuerService();
issuerService.setIssuer(issuer);
return issuerService;
}
#Bean(name = "clientConfigurationService")
public ClientConfigurationService clientConfigurationService() {
StaticClientConfigurationService clientConfigService = new StaticClientConfigurationService();
clientConfigService.setClients(registeredClient());
return clientConfigService;
}
#Bean(name = "clients")
public Map<String, RegisteredClient> registeredClient() {
Map<String, RegisteredClient> oidcRegClients = new HashMap<String, RegisteredClient>();
oidcRegClients.put(issuer, new RegisteredClient(client));
return oidcRegClients;
}
#Bean(name = "authRequestUrlBuilder")
public AuthRequestUrlBuilder authRequestUrlBuilder() {
return new PlainAuthRequestUrlBuilder();
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(openIdConnectAuthenticationFilter(), AbstractPreAuthenticatedProcessingFilter.class)
.formLogin()
.loginPage("/openid_connect_login")
.and()
.logout()
.and()
.authorizeRequests()
.antMatchers("/items")
.authenticated()
.anyRequest()
.permitAll();
}
}
You are on right path. I think, your question is how to extract the information(for e.g. username) from cookie and then use this information to authorize the user. Here are the steps, to clear some air.
Configure a subclass of AbstractPreAuthenticatedProcessingFilter (e.g. below )
public class CustomPreAuthenticatedFilter extends AbstractPreAuthenticatedProcessingFilter {
protected Object getPreAuthenticatedPrincipal(HttpServletRequest request) {
// below sample extracts the username from header.You can pull from cookie
String expectedHeaderNameContainingUsername = "abcd";
String username = request.getHeader(expectedHeaderNameContainingUsername);
return username;
}
protected Object getPreAuthenticatedCredentials(HttpServletRequest request) {
String expectedHeaderNameContainingCredentials = "";
if (StringUtils.isNotBlank(expectedHeaderNameContainingCredentials)) {
return request.getHeader(expectedHeaderNameContainingCredentials);
}
return "N/A";
}
}
Simply register the above filter with HTTP security with
http.addFilter(Filter filter);
It seems your filter is not registered with spring security.
The AbstractPreAuthenticatedProcessingFilter forwards the result of getPreAuthenticatedPrincipal(..) to authmanager to build the principal object.
Hope this helps.

Resources