Springboot with Keycloak always return 403 - spring-boot

I have created a Springboot application with Keycloak by following this tutorial Baeldung
When I try to enter /api/foos it always returns 403 without any error messages.
// SecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, jsr250Enabled = true, prePostEnabled = true)
class SecurityConfig(
private val unauthorizedHandler: JwtAuthenticationEntryPoint
) : WebSecurityConfigurerAdapter() {
#Throws(Exception::class)
override fun configure(http: HttpSecurity) {
http
.cors()
.and()
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/user/info", "/api/foos/**", "/api/foos")
.hasAnyRole("free_user")
.antMatchers(HttpMethod.POST, "/api/foos")
.hasAnyRole("free_user")
.anyRequest()
.authenticated()
.and()
.oauth2ResourceServer()
.jwt()
}
}
// Controller
#RestController
#RequestMapping(value = ["/api/foos"])
class SecurityTestController() {
#GetMapping(value = ["/{id}"])
fun findOne(#PathVariable id: Long?): String {
return "fineOne with id $id"
}
#GetMapping
fun findAll(): Message {
return Message("findAll")
}
}
// application.properties
# Resource server config
rest.security.issuer-uri=http://localhost:8081/auth/realms/dev
spring.security.oauth2.resourceserver.jwt.issuer-uri=${rest.security.issuer-uri}
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=${rest.security.issuer-uri}/protocol/openid-connect/certs
// build.gradle (app)
plugins {
id("org.springframework.boot")
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter- oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-security")
testImplementation("org.springframework.security:spring-security-test")
}
Here is my user on Keycloak
Postman result:
What I have already tried
disable csrf - Not working
Comment SecurityConfig class - Working without security

It looks like "free_user" is a client role.
Two solutions :
Either remove the current "free_user" client role, create a "free_user" realm role in the global Roles tab, and assign it to your user.
Or, add the property keycloak.use-resource-role-mappings=true to your Spring boot configuration to allow spring security to map your current client role.

I found the answer here LINK
We need to create a custom mapping between Spring security and Keycloak roles.
public class KeycloakRealmRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
#Override
public Collection<GrantedAuthority> convert(Jwt jwt) {
final Map<String, Object> realmAccess = (Map<String, Object>) jwt.getClaims().get("realm_access");
return ((List<String>)realmAccess.get("roles")).stream()
.map(roleName -> "ROLE_" + roleName) // prefix to map to a Spring Security "role"
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
}

Related

Spring-Security OAUTH2 and PKCE, IdentityServer4 How do I add code_challenge info

I am trying to access Identity Server. When I try to access I get an error that says
MessageTemplate: code_challenge is missing
I have a basic Spring Boot Application. How do I get the app to add in the Code Challenge and code Challenge type.
I have tried to add in this:
#Configuration
public class OAuth2ClientConfiguration {
#Bean
public SecurityWebFilterChain pkceFilterChain(ServerHttpSecurity http, ServerOAuth2AuthorizationRequestResolver resolver) {
http.authorizeExchange(r -> r.anyExchange().authenticated());
http.oauth2Login(auth -> auth.authorizationRequestResolver(resolver));
return http.build();
}
#Bean
public ServerOAuth2AuthorizationRequestResolver pkceResolver(ReactiveClientRegistrationRepository repo) {
DefaultServerOAuth2AuthorizationRequestResolver resolver = new DefaultServerOAuth2AuthorizationRequestResolver(repo);
resolver.setAuthorizationRequestCustomizer(OAuth2AuthorizationRequestCustomizers.withPkce());
return resolver;
}
but that causes an error saying that
Description:
Parameter 0 of method pkceFilterChain in com.landstar.security.poc.securitypoc.config.OAuth2ClientConfiguration required a bean of type 'org.springframework.security.config.web.server.ServerHttpSecurity' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.security.config.web.server.ServerHttpSecurity' in your configuration.
Additional Info
#Configuration
#EnableWebSecurity
public class SecurityConfig {
private static final String[] WHITE_LIST_URLS = {
"/user",
"/helloPublic",
"/register",
"/verifyRegistration*",
"/resendVerifyToken*"
};
#Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeHttpRequests()
.antMatchers(WHITE_LIST_URLS).permitAll()
.antMatchers("/api/**").authenticated()
.and()
.oauth2Login(oauth2login ->
oauth2login.loginPage("/auth2/authorization/landstar"))
.logout(l -> l
.logoutSuccessUrl("/").permitAll()
)
.oauth2Client(Customizer.withDefaults());
return http.build();
}
}
Please, any help.!!! thanks

Spring Security not working on any endpoint with multiple WebSecurityConfigurerAdapter implementations

I'm trying to setup Spring Security in my application, which has 3 components:
REST API (under v1 path)
Spring Admin & actuator (under /admin path)
Docs (under /docs and /swagger-ui paths)
I want to setup security like this:
REST API secured with JWT token
Admin secured with HTTP basic
Docs unsecured (public resource)
I've tried to configure authentication for those 3 parts in separate implementations of WebSecurityConfigurerAdapter, and the result looks like this:
For REST API:
#Configuration
#EnableWebSecurity
#Order(1)
class ApiWebSecurityConfig : WebSecurityConfigurerAdapter() {
// FIXME: Temporary override to disable auth
public override fun configure(http: HttpSecurity) {
http
.antMatcher("/v1/*")
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.anyRequest().permitAll()
.and()
.csrf().disable()
}
}
For Spring Admin:
#Configuration
#EnableWebSecurity
#Order(2)
class AdminWebSecurityConfig(
private val adminServerProperties: AdminServerProperties
) : WebSecurityConfigurerAdapter() {
public override fun configure(http: HttpSecurity) {
http.antMatcher("${adminServerProperties.contextPath}/**")
.authorizeRequests()
.antMatchers("${adminServerProperties.contextPath}/assets/**").permitAll()
.antMatchers("${adminServerProperties.contextPath}/login").permitAll()
.anyRequest()
.authenticated()
.and()
.cors()
.and()
.formLogin()
.loginPage("${adminServerProperties.contextPath}/login")
.and()
.logout()
.logoutUrl("${adminServerProperties.contextPath}/logout")
.and()
.httpBasic()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
AntPathRequestMatcher("${adminServerProperties.contextPath}/instances", HttpMethod.POST.toString()),
AntPathRequestMatcher("${adminServerProperties.contextPath}/instances/*", HttpMethod.DELETE.toString()),
AntPathRequestMatcher("${adminServerProperties.contextPath}/actuator/**")
)
}
#Bean
fun corsConfigurationSource(): CorsConfigurationSource = UrlBasedCorsConfigurationSource().apply {
registerCorsConfiguration("/**", CorsConfiguration().apply {
allowedOrigins = listOf("*")
allowedMethods = listOf("HEAD", "GET", "POST", "PUT", "DELETE", "PATCH")
allowCredentials = true
allowedHeaders = listOf("Authorization", "Cache-Control", "Content-Type")
})
}
}
And for public docs:
#Configuration
#EnableWebSecurity
#Order(3)
class DocsWebSecurityConfig : WebSecurityConfigurerAdapter() {
public override fun configure(http: HttpSecurity) {
http
.requestMatchers()
.antMatchers("/swagger-ui/**", "/docs/**", "/docs-oas3/**")
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
}
}
And my main application class looks like this:
#SpringBootApplication
#EnableAdminServer
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#EnableConfigurationProperties(FirebaseConfigurationProperties::class, JwtConfigurationProperties::class)
class HldpDeviceManagementApplication
fun main(args: Array<String>) {
runApplication<HldpDeviceManagementApplication>(*args)
}
When I run the application, there's no error or any security information, besides this log output:
Will not secure Ant [pattern='/v1/**']
Will not secure Ant [pattern='/admin/**']
Will not secure Or [Ant [pattern='/swagger-ui/**'], Ant [pattern='/docs/**'], Ant [pattern='/docs-oas3/**']]
Any suggestion why doesn't the configuration work? Or maybe another way I can secure the application like this? I've tried doing a few changes in the configuration, but nothing seems to help.
I've found the problem - it's a bug in the latest version of Spring:
https://github.com/spring-projects/spring-security/issues/10909
You didn't mention when it doesn't work, is it when you make a request, or on application startup? However, I can help you with your configuration and get the information needed to solve the problem.
I'll try to simplify your configuration with the new way to configure HttpSecurity, by exposing a SecurityFilterChain bean.
#Configuration
public class SecurityConfiguration {
#Bean
#Order(0)
public SecurityFilterChain api(HttpSecurity http) throws Exception {
http
.requestMatchers(requests -> requests.antMatchers("/v1/**"))
...
// the rest of the configuration
return http.build();
}
#Bean
#Order(1)
public SecurityFilterChain admin(HttpSecurity http) throws Exception {
http
.requestMatchers(requests -> requests.antMatchers("/admin/**"))
...
// the rest of the configuration
return http.build();
}
#Bean
#Order(2)
public SecurityFilterChain docs(HttpSecurity http) throws Exception {
http
.requestMatchers(requests -> requests.antMatchers("/docs/**"))
...
// the rest of the configuration
return http.build();
}
}
This is in Java, but you can adapt to Kotlin easily, I'm sorry to not provide it in Kotlin already. With this simplified configuration, now you can add logging.level.org.springframework.security=TRACE to your application.properties file and check what Spring Security is doing by reading the logs.

Spring: Using Oauth2 and HttpBasicAuth together

I'm using Spring Boot 2.0.0
For securing my REST API i'm using Oauth2 with JWT, which works perfectly fine.
The problem is:
I'm also using Springfox Swagger which should be secured by BasicAuth. So that the user is challenged if he points his browser to /swagger-ui.html
Therefore i got two configuration files:
SecurityConfig
#Configuration
#EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
#Throws(Exception::class)
override fun configure(web: WebSecurity) {
web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**")
}
#Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
//user: "user", password: "Passw0rd!"
.withUser("user")
.password("\$2a\$04\$DDYoNw1VAYt64.zU.NsUpOdvjZ3OVrGXJAyARkraaS00h322eL2iy")
.roles("ADMIN")
}
}
ResourceServerConfig
#Configuration
#EnableResourceServer
class ResourceServerConfig : ResourceServerConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
super.configure(http)
http.httpBasic().and().cors().and().csrf().disable()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.antMatcher("/swagger-ui.html**")
.authorizeRequests().anyRequest().hasRole("ADMIN")
}
}
I think the OAuth2AuthorizationServerConfig is not needed here.
The shown configuration (of course) doesn't work, so the question is:
Is it possible to mix BasicAuth and Oauth2?
Ok, i more or less found an answer to my question:
SecurityConfig
#Configuration
#EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
#Throws(Exception::class)
override fun configure(auth: AuthenticationManagerBuilder) {
auth.inMemoryAuthentication()
//user: "user", password: "Passw0rd!"
.withUser("user")
.password("...")
.roles("ADMIN")
}
override fun configure(http: HttpSecurity) {
http.csrf()
.and()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers(
"/swagger-ui.html**").hasRole("ADMIN")
.antMatchers(
"/v2/api-docs",
"/swagger-resources/**",
"/configuration/security", "/webjars/**"
).permitAll()
}
}
ResourceServerConfig
#Configuration
#EnableResourceServer
class ResourceServerConfig : ResourceServerConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http.cors().and()
.antMatcher("/api")
.authorizeRequests().antMatchers("/api/**").authenticated()
}
}
I'm using antMatcher in the ResourceServerConfig to protect only the /api/** paths with oauth2.
The BasicAuth part happens in SecurityConfig.
The current solution only applies the BasicAuth only to the /swagger-ui.html endpoint. The other swagger resources are public visible.
Does anyone know a way to also protect /v2/api-docs?
It's all about matching security configurations onto different application context paths. See my answer at Run a Spring Boot oAuth2 application as resource server AND serving web content - I hope this helps.

Spring Boot Authorization Basic Header Never Changes

I am attempting to setup a very basic spring boot authenticated application. I am setting the Authorization header in the client and sending it to the backend. I can verify that the client is sending the correct header.
The backend receives the header correctly on the first attempt to login. However if the login credentials are incorrect subsequent requests retain whatever the header for the intial request was (caching it or something).
I am using Redis to Cache the session. My config is as follows:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired AuthenticationEntryPoint authenticationEntryPoint;
#Autowired CsrfTokenRepository csrfTokenRepository;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf()
.disable()
.authorizeRequests().antMatchers("**")
.permitAll()
.anyRequest()
.authenticated()
;
}
}
AuthenticationEntryPoint
public class AuthenticationEntryPointBean {
#Bean
AuthenticationEntryPoint authenticationEntryPoint() {
return new RestAuthenticationEntryPoint();
}
}
Any direction would be appreciated.
** Edit **
Adding cache settings
#Configuration
#EnableRedisHttpSession
public class HttpSessionConfig {
#Bean
public JedisConnectionFactory connectionFactory() {
return new JedisConnectionFactory(); // <2>
}
}
Also I am trying to invalidate cache but that doesn't seem to work
#CrossOrigin
#RequestMapping(value="/auth/login", method = RequestMethod.GET, produces="application/json")
public #ResponseBody String login(#RequestHeader(name = "authorization") String authorization, HttpSession session, HttpServletRequest request)
{
try
{
authorization = authorization.substring("Basic ".length());
String decoded = new String(Base64.getDecoder().decode(authorization),"UTF-8");
Gson gson = new Gson();
LoginRequest login = gson.fromJson(decoded,LoginRequest.class);
UserAuthenticationEntity entity = service.getSecurityContext(login).orElseThrow(() ->
new BadCredentialsException("Authentication Failed.")
);
session.setMaxInactiveInterval((int)TimeUnit.MINUTES.toSeconds(expiresInMinutes));
SecurityContextHolder.getContext().setAuthentication(new EntityContext(entity,expiresInMinutes));
String response = gson.toJson(BasicResponse.SUCCESS);
return response;
}
catch (Exception e)
{
session.invalidate();
e.printStackTrace();
throw new AuthenticationCredentialsNotFoundException("Authentication Error");
}
}
Adding the following to my web security config seemed to do the trick.
.requestCache()
.requestCache(new NullRequestCache())
I am not sure what side effects are of doing this. I picked it up off of a blog https://drissamri.be/blog/2015/05/21/spring-security-and-spring-session/
If there is any more insight into if this is good practice or bad practice I would appreciate any comments.
My final web security config looks like the following:
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.csrf()
.disable()
.authorizeRequests().antMatchers("**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.requestCache()
.requestCache(new NullRequestCache())
.and()
.sessionManagement()
.sessionFixation()
.newSession()
;

How to set redirect url after success login using Social Providers

I need change the redirect url when my user is succefull logged in using some of Spring Social Providers, like Twitter in this case.
I'm getting in every set***Url("") a null pointer exception
Some times setting this don't work too
I tried so far setting:
public ProviderSignInController signInController(ConnectionFactoryLocator connectionFactoryLocator,
UsersConnectionRepository usersConnectionRepository) {
ProviderSignInController providerSignInController = new ProviderSignInController(connectionFactoryLocator,
usersConnectionRepository,
new CSignInAdapter(requestCache()));
providerSignInController.setPostSignInUrl("/home");
providerSignInController.setApplicationUrl("localhost:8080/home");
return providerSignInController;
}
I tried each one of setPostSignInUrl and setApplicationUrl, separately.
Also tried:
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
ConnectController connectController = new ConnectController(connectionFactoryLocator, connectionRepository);
connectController.addInterceptor(new TweetAfterConnectInterceptor());
connectController.setApplicationUrl("/home");
return connectController;
}
I'm using Spring Social showcase with Security as base to do this.
In case of need I'm posting the HttpSecurity configuration:
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.loginPage("/signin")
.loginProcessingUrl("/signin/authenticate")
.failureUrl("/signin?param.error=bad_credentials")
.defaultSuccessUrl("/home")
.and()
.csrf()
.and()
.logout()
.logoutUrl("/signout")
.deleteCookies("JSESSIONID")
.and()
.authorizeRequests()
.antMatchers("/admin/**", "/favicon.ico", "/resources/**", "/auth/**", "/signin/**", "/signup/**",
"/disconnect/facebook").permitAll()
.antMatchers("/**").authenticated()
.and()
.rememberMe()
.and()
.apply(new SpringSocialConfigurer());
}
Try this:
private SpringSocialConfigurer getSpringSocialConfigurer() {
SpringSocialConfigurer config = new SpringSocialConfigurer();
config.alwaysUsePostLoginUrl(true);
config.postLoginUrl("/home");
return config;
}
Then change your configure method:
.apply(getSpringSocialConfigurer());
For Spring Social, you can configure the post login URL to a default URL, such as "/home".
But under certain circumstances, you would like to direct the user to a different URL. In order to dynamically change the redirect URL after successful login, you can simply return a String representing any URL you desire in the signIn method of your SignInAdapter implementation class:
import org.springframework.social.connect.web.SignInAdapter;
public class SocialSignInAdapter implements SignInAdapter {
public String signIn(String localUserId, Connection<?> connection, NativeWebRequest request) {
boolean flag = true;
if (flag) {
return "/a_different_url";
}
return null; // Default, which means using the default post login URL
}
}
I verified this using Spring Social version 1.1.0.RELEASE

Resources