Spring Boot OAuth2 ResourceServer 401 with PermitAll - spring-boot

the setup is like this: as authentication server I got a Keycloak, as API-Gateway I use spring-cloud-gateway with Netflix Eureka Client as DiscoveryClient. Of course I need usermanagement, a "simple" register for not authenticated people and registering people as user with admin role. The WebSecurityConfig of the resource-server (Usermanagementservice) looks like this:
#EnableGlobalMethodSecurity(securedEnabled=true, prePostEnabled=true)
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception
{
JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new KeycloakRoleConverter());
http
.authorizeRequests()
.antMatchers("/register/**")
.permitAll()
.and()
.authorizeRequests()
.antMatchers("/usermanagementservice/**")
.hasAnyRole("admin", "anotherrole")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.jwt()
.jwtAuthenticationConverter(jwtAuthenticationConverter);
}
}
The RegisterController looks like this:
#RestController
#RequestMapping("/register")
public class RegisterController {
#Autowired
private Service service;
#GetMapping("/status")
public boolean checkStatus()
{
return true;
}
#PostMapping("/create")
public Response createUser(#RequestBody User user)
{
return service.doSomething(user);
}
}
So if everything is running, and i make the getRequest to my API-Gateway on localhost:8083/register/status I get the boolean back as response, if I send a POST-Request to the Gateway with a Json-Object I get the 401 Unauthorized, I added at the WebSecurityConfig the #Order(1) annotation, nothing changed, like here. I tried and read this, that and this one and not to forget that one. But no luck at all. :( Any help would be appreciated. Thank you very much in advance. :)

http
.csrf().disable()
was the missing piece in the configure method of the WebSecurityConfig.class Thank you very much #jzheaux for guiding.

Related

Spring Security: don't redirect to login page in case unauthorised

I have Spring Security with oAuth2 authorisation.
I use it for REST API.
My configuration:
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.authorizeRequests()
.antMatchers("/health").permitAll()
.antMatchers("/**").authenticated()
.and()
.oauth2Login()
.and()
.httpBasic();
}
}
I need to make all requests return me 401 when I didn't authorise.
But now when I'm not authorised I got redirect to /login page.
I need to use it like usual REST API: if I did authorise then get content, otherwise get 401 Unauthorised.
How I can make it?
Thanks in addition for help.
Basically you need to configure an AuthenticationEntryPoint which is invoked when Spring Security detects a non-authenticated request. Spring also gives you a handy implementation which enables you to return whatever HttpStatus you need:
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
//rest of your config...
.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}

Spring Boot AntMatchers vs #PostAuthorize usage

I'm tasked with implementing RBAC(Role-Based Access Control) in the REST API I'm working on.
What puzzles me is that when I use in my Security class that extends WebSecurityConfigurerAdapter, in configure method antMatchers, the Authorisation is working correctly, but when I dispose of antMatchers and try to replace them by #PostAuthorize on top of an endpoint, RBAC fails to work.
That's my configure method from a class extending WebSecurityConfigurerAdapter:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.rememberMe()
.and()
.addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager()))
.addFilterAfter(new JwtTokenVerifierFilter(), JwtUsernameAndPasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/user").authenticated()
.antMatchers("/hello").hasRole(ApplicationUserRole.ADMIN.name())
.anyRequest()
.authenticated();
http.headers().frameOptions().disable();/*REQUIRED FOR H2-CONSOLE*/
}
Which works fine.
Thats by annotarion on top of an endpoint that shoud be authorized, but is not.
#PostAuthorize("hasRole('ADMIN')")
#RequestMapping("/hello")
String hello(){
return "hello";
}
What am I doing wrong, that it is not workind correctly?
Did you try annotating your security config class with the below annotations?
Something like this.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(final HttpSecurity http) throws Exception {}
}

Spring Security redirecting custom login page to itself - Too Many Redirects

I'm currently developing a custom login-page for my Spring Boot Application but I just can't get it to work. Using the default one works fine but as soon as I try to use my custom file, it just repeatedly redirects me until my Browser give up.
Other posts suggest permitting access to the login-path to erveryone but this also doesn't seem to work.
Here is my code:
WebSecurityConfig
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
}
And Controller for login-page
#Controller
public class WebController {
#GetMapping("/login")
public String login () {
return "login";
}
}
Any ideas what I'm missing?
You are probably using a lot of CSS and JS file link links, according to your code Spring Boot must first authenticate all the links, which is why it redirects to your login page many times.
add following code to bypass security authentication of resource link
public void configure(WebSecurity web) {
web.ignoring()
.antMatchers("/bower_components/**", "/dist/**", "/plugins/**"); //write your resource directory name
}

Spring Security ignore few urls few urls basic auth remaining all JWTTokenAuth

In my application, i need to implement different spring securities based on different URL. for /app/healthcheck need to ignore security, for /app/manage need to have basic authentication, for remaining all other /api/** need JWT Token authentication. Implemented like below
#Configuration
#EnableWebSecurity
public class WebSecurityConfig {
#Bean
WebSecurityConfigurerAdapter defaultConfig() {
return new WebSecurityConfigurerAdapter() {
#Override
protected void configure(HttpSecurity http) throws Exception {
configureHttpSecurity(http.csrf().disable().headers().frameOptions().disable().and(),
authenticationManager());
}
};
}
void configureHttpSecurity(HttpSecurity http, AuthenticationManager authenticationManager) throws Exception {
http.authorizeRequests().antMatchers("/app/healthcheck").permitAll().anyRequest()
.authenticated().and()
.addFilterBefore(new MyJWTAuthenticationFilter(authenticationManager),
UsernamePasswordAuthenticationFilter.class)
.logout().permitAll();
}
#Bean
public UserAuthenticationProvider springAuthenticationProvider() {
return new UserAuthenticationProvider();
}
}
#Configuration
#EnableWebSecurity
#Order(Ordered.HIGHEST_PRECEDENCE)
public class BasicSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors();
http.antMatcher("/app/manage")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
}
in application.yml added
spring:
profiles: dev
security:
user:
name: ${admin}
password: ${password}
when i run the app, /app/healthcheck ignoring security, remaining all other asking for JWT authentication. but /app/manage also triggering JWT authentication instead of basic auth. If i comment Token auth, basic is working perfect.
am new to spring security please let me know what am i missing.
Thank You.

Adding spring security to Zuul service in spring boot micro service

I am new to micro service architecture.
We have few services like zuul service (api gateway), security service (connect to db check access) and xyz service.
I would like to know, how we can add spring security to the routes defined in the zuul service. ?
On defining authorizeRequests like below on zuul service, it should call security service internally and authenticate the requests.
Example:
.authorizeRequests()
.antMatchers("/user/count").permitAll()
.antMatchers("/user/**").authenticated()
Note: /user End point is defined in the security service.
Please help me with this.
Our Zuul proxy is supporting OAuth2 security. An example of the security config is this:
#Configuration
#EnableResourceServer
public class JwtSecurityConfig extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/oauth/**").permitAll()
.antMatchers("/**").hasAuthority("ROLE_API_ACCESS")
.and()
.csrf().disable();
}
}
I would assume if you are doing basic auth you could do something similar using the appropriate class. Maybe something like this.
#Configuration
#Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
BasicAuthenticationEntryPoint authenticationEntryPoint = new BasicAuthenticationEntryPoint();
authenticationEntryPoint
.setRealmName("EnterpriseDeviceAuthentication");
http
.authorizeRequests()
.antMatchers("/health").permitAll() // allow access to health page
.antMatchers("/somepath").permitAll()
.antMatchers("/somepath2").permitAll()
.antMatchers("/bootstrap.min.css").permitAll()
.anyRequest().hasAnyAuthority(SecurityRoles.ALL_SECURITY_ROLES)
.and().httpBasic()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf().disable();
}
}

Resources