Jhipster public api encounter Unauthorized status 401 - spring-boot

My Project needs to set up a callback API to receive a biometric punchlog. I exposed a public API [.antMatchers("/api/daily-time-records").permitAll()] but I encounter error when I test it in postman
"type": "https://www.jhipster.tech/problem/problem-with-message",
"title": "Unauthorized",
"status": 401,
"detail": "Full authentication is required to access this resource",
"path": "/api/daily-time-records%0A",
"message": "error.http.401"
Resource
#PostMapping("/daily-time-records")
public ResponseEntity<DailyTimeRecordDTO> createDailyTimeRecord(#Valid #RequestBody DailyTimeRecordDTO dailyTimeRecordDTO)
throws URISyntaxException {
log.debug("REST request to save DailyTimeRecord : {}", dailyTimeRecordDTO);
if (dailyTimeRecordDTO.getId() != null) {
throw new BadRequestAlertException("A new dailyTimeRecord cannot already have an ID", ENTITY_NAME, "idexists");
}
DailyTimeRecordDTO result = dailyTimeRecordService.save(dailyTimeRecordDTO);
return ResponseEntity
.created(new URI("/api/daily-time-records/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
Security Configuration
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.contentSecurityPolicy(jHipsterProperties.getSecurity().getContentSecurityPolicy())
.and()
.referrerPolicy(ReferrerPolicyHeaderWriter.ReferrerPolicy.STRICT_ORIGIN_WHEN_CROSS_ORIGIN)
.and()
.permissionsPolicy().policy("camera=(), fullscreen=(self), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), sync-xhr=()")
.and()
.frameOptions()
.deny()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/daily-time-records").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN)
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/health/**").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/prometheus").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.httpBasic()
.and()
.apply(securityConfigurerAdapter());
// #formatter:on
}

Related

Disable multiple logins for same user in spring boot

HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
protected void configure(final HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers(
"/getUser",
"/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/swagger-ui.html",
"/webjars/**"
,"/**/user/reset-password-first-attempt"
,"/**/user/forget-password-email"
,"/**/user/forget-password"
).permitAll()
.mvcMatchers(
"/css/**",
"/images/**",
"/fonts/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.successHandler(this.successHandler())
.failureHandler(this.customAuthenticationHandler)
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler())
.and()
.exceptionHandling()
.accessDeniedHandler(this.accessDeniedHandler())
.authenticationEntryPoint(this.authenticationEntryPoint())
.and()
.sessionManagement()
.maximumSessions(1).maxSessionsPreventsLogin(true);}
this is the code that i am using to disable multiple logins. i saw some several examples and i tried most of them. but those didnt work in my application. is there any other solution or is there any wrong with my code. thanks in advance

403 Bad Request sending a post request from URI with name parameter

I have my post request filtered after JWT Authentication (and even if I disable it as following code). Not sure if I do anything wrong.
URI REQUEST: localhost:8016/api/v1/VILLA+ITALIA/table
PARAMETER: name
enter image description here
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable().formLogin().disable()
.csrf().ignoringAntMatchers(API_URL_PREFIX, H2_URL_PREFIX)
.and()
.headers().frameOptions().sameOrigin() // for H2 Console
.and()
.cors()
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, RESTAURANT_URL).permitAll()
.antMatchers(HttpMethod.POST, RESTAURANT_URL).permitAll()
.antMatchers(HttpMethod.POST, TOKEN_URL).permitAll()
.antMatchers(HttpMethod.DELETE, TOKEN_URL).permitAll()
.antMatchers(HttpMethod.POST, SIGNUP_URL).permitAll()
.antMatchers(HttpMethod.POST, REFRESH_URL).permitAll()
.antMatchers(HttpMethod.GET, SERVICES_URL).permitAll()
.antMatchers(HttpMethod.POST, SERVICES_URL).permitAll()
.antMatchers(HttpMethod.GET, BOOKINGS_URL).permitAll()
.antMatchers(HttpMethod.POST, BOOKINGS_URL).permitAll()
.antMatchers(HttpMethod.GET, CUSTOMERS_URL).permitAll()
.antMatchers(HttpMethod.POST, CUSTOMERS_URL).permitAll()
.antMatchers(HttpMethod.POST, TABLES_URL).permitAll()
// .mvcMatchers(HttpMethod.POST, "/api/v1/restaurants**")
// .hasAuthority(RoleEnum.ADMIN.getAuthority())
.anyRequest().authenticated()
.and()
//.addFilterBefore(new JwtAuthenticationFilter(new JwtManager(), (UserService) userService), UsernamePasswordAuthenticationFilter.class)
// .oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer.jwt(
// jwt -> jwt.jwtAuthenticationConverter(getJwtAuthenticationConverter())))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
} ```
There are nothing antMatchers sentence which match with "/api/v1/VILLA+ITALIA/table" url.
Try it using the following sentence:
.antMatchers(HttpMethod.GET, "/api/v1/**/table").permitAll()

Setting a DefaultAuthenticationEventPublisher in WebSecurityConfigurerAdapter for Spring Security 5

I've updated some of our services to Spring Security 5 from a SS 4 version where it had external support for OAuth2. I've been able to update our services for the most part.
Previously our WebSecurityConfigurerAdapter had the following configure function where we set an applicationEventPublisher on a OAuth2AuthenticationProcessingFilter so we can output logs messages about AuthenticationEvents.
But OAuth2AuthenticationProcessingFilter went away in SS5 because OAuth2 support is now directly supported.
Is their an easier way of setting the AuthenticationEventPublisher without creating my own filter and recreating the part of checking authentication to just have it done again by Spring?
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
OAuth2AuthenticationProcessingFilter filter = new OAuth2AuthenticationProcessingFilter();
filter.setAuthenticationManager(authenticationManager);
filter.setStateless(true);
filter.setAuthenticationEventPublisher(
new DefaultAuthenticationEventPublisher(applicationEventPublisher));
filter.afterPropertiesSet();
http.csrf()
.disable()
.anonymous()
.disable()
.httpBasic()
.disable()
.logout()
.disable()
.formLogin()
.disable()
.addFilterBefore(filter, SessionManagementFilter.class)
.antMatcher("/actuator/**")
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers("/actuator/**")
.access("#oauth2.hasScope('auditor')")
.anyRequest()
.authenticated()
.accessDecisionManager(accessDecisionManager);
}
#Bean
public ApplicationListener<AuditApplicationEvent> onEventListener() {
return (AuditApplicationEvent event) -> {
LoggingUtil loggingFormat = new LoggingUtil();
loggingFormat.setUser(event.getAuditEvent().getPrincipal());
loggingFormat.setEvent("Resource Authentication");
loggingFormat.setOutcome(event.getAuditEvent().getType());
loggingFormat.setMessage(
event.getAuditEvent().getData().containsKey("message")
? event.getAuditEvent().getData().get("message").toString()
: "");
String info = loggingFormat.toString();
logger.info(info);
};
}
For our SS 5 we have
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
SessionManagementFilter as;
//TODO how do we setup the authenticationEventPublisher
//filter.setAuthenticationEventPublisher(
// new DefaultAuthenticationEventPublisher(applicationEventPublisher));
http.csrf()
.disable()
.anonymous()
.disable()
.httpBasic()
.disable()
.logout()
.disable()
.formLogin()
.disable()
// .addFilterBefore(filter, SessionManagementFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS)
.permitAll()
.antMatchers("/actuator/**").hasAuthority("SCOPE_auditor")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer().jwt();
}

Why the character ';' is added the end of request in OAuth2

There are Authorization Server(UAA) and Resource Server and Gateway applications that have been working correctly. The scenario for authentication is authorization_code. In the first time after authentication, the end of request is added ;jesessionid=[value], so its result is exception from HttpFirewall of Gateway application, because of having ';' in the request.
My question is that what is it and why jessionid is added the end of request? and how is it adaptable with HttpFirewall.
I have found a way around but I know it has some risks. It is like this:
#Bean
public HttpFirewall allowUrlEncodedSlashHttpFirwall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowSemicolon(true);
return firewall;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.headers().cacheControl().disable()
.and()
.headers()
.cacheControl()
.disable()
.frameOptions()
.sameOrigin()
.and()
.httpBasic().disable()
.authorizeRequests()
.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()
.requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
.mvcMatchers("/uaa/**", "/login**", "/favicon.ico", "/error**").permitAll()
.anyRequest().authenticated()
.and()
.logout()
.permitAll();
}
#Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
web.httpFirewall(allowUrlEncodedSlashHttpFirwall());
}
As above configuration, the ; is skipped but it is not right and it has some risks.
What is the correct way and config to solve this problem?

Spring Security Ignores all requests when you should just ignore the OPTIONS requests

Before GET/POST request the client make a OPTIONS request, so I keep this calls ignored. But when I make this configuration, the another requests(GET/POST) are ignored too (but should not ignore).
When I add this line:
.antMatchers(HttpMethod.OPTIONS);
All requests are ignored, but the GET/POST should not ignored.
The following is the configuration method:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.POST, "/login")
.antMatchers(HttpMethod.OPTIONS);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest().authenticated()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers(HttpMethod.GET, "/login/authenticate").authenticated()
.antMatchers(HttpMethod.GET, "/credenciadas**").hasRole(PermissaoEnum.CONSULTAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas/validar").hasRole(PermissaoEnum.CONSULTAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas").hasRole(PermissaoEnum.INCLUIR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.POST, "/credenciadas/alterar").hasRole(PermissaoEnum.ALTERAR_CREDENCIADA.getNomeInterno())
.antMatchers(HttpMethod.DELETE, "/credenciadas/").hasRole(PermissaoEnum.EXCLUIR_CREDENCIADA.getNomeInterno())
.and()
.addFilterBefore(authenticationByTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().disable();
}
Could you verify if you set the prefix string at role name as: "ROLE_"? The role name could be wrong.

Resources