How to override the Spring Boot default OAuthTokenEndpoint - spring-security

I've been working on securing a Restful Service using Spring Security Oauth. I've been banging my head trying to secure the /oauth/token endpoint using SSL and only allowing for POST calls.
I'm using #EnableAuthorizationServer which states
Convenience annotation for enabling an Authorization Server (i.e. an
AuthorizationEndpoint and a TokenEndpoint) in the current application
context, which must be a DispatcherServlet context. Many features of
the server can be customized using #Beans of type
AuthorizationServerConfigurer (e.g. by extending
AuthorizationServerConfigurerAdapter). The user is responsible for
securing the Authorization Endpoint (/oauth/authorize) using normal
Spring Security features (#EnableWebSecurity etc.), but the Token
Endpoint (/oauth/token) will be automatically secured using HTTP Basic
authentication on the client's credentials. Clients must be registered
by providing a ClientDetailsService through one or more
AuthorizationServerConfigurers.
Which is great, but I can't seem to override the token endpoint piece or enforce POST-only calls, like with the intercept-url xml syntax
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore()
}
#Autowired
AuthenticationManager authenticationManager
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints
.tokenStore(tokenStore())
.authenticationManager(authenticationManager);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient('testApp')
.scopes("read", "write")
.authorities('ROLE_CLIENT')
.authorizedGrantTypes("password","refresh_token")
.secret('secret')
.accessTokenValiditySeconds(7200)
}
}
I secured my Resource server with
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Autowired
private RestAuthenticationEntryPoint authenticationEntryPoint;
#Override
public void configure(HttpSecurity http) throws Exception {
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.requiresChannel().anyRequest().requiresSecure()
.and()
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/**").authenticated()
}
}
Is there a similar builder syntax for the Authorization Servers TokenEndpoint security that uses requiresChannel?

I ended up creating my own config using
org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerSecurityConfiguration
Since i'm using Spring boot I just autowired the SecurityProperties and added this line for the SSL on the Oauth endpoints
if (this.security.isRequireSsl()) {
http.requiresChannel().anyRequest().requiresSecure();
}
And for the POST requirement
http
.authorizeRequests()
.antMatchers(HttpMethod.POST,tokenEndpointPath).fullyAuthenticated()
.antMatchers(HttpMethod.GET,tokenEndpointPath).denyAll()
Afterwards removed the #EnableAuthorizationServer so it would use my config.

Related

Getting unauthorized after login in spring boot reactive

I'm trying to create form login with spring boot webflux. I can login and after login I'm redirectored successfully. But when I browse to a page that requires authentication, I'm getting error. If I remove the page from security config and get principal from ReactiveSecurityContextHolder I'm getting the user details.
Here is my security config:
public class SecurityConfig {
#Autowired
private UserService userService;
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/"))
.authenticationManager(reactiveAuthenticationManager())
.and()
.logout()
.and()
.build();
}
#Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null));
}
}
Do I need to do anything else in the ReactiveAuthenticationManager? Is that even required?
In this repository : https://github.com/mohamedanouarbencheikh/dashboard-auth-microservice
you have a complete example of spring security implementation with jwt in microservice architecture using spring cloud routing (gateway) which is based on reactive programming and Netty as application server, and angular as frontend
Answering to my own question so that anyone facing same problem can get some help:
The issue was resolved when I've changed the UsernamePasswordAuthenticationToken constructor and passed the authority parameter as null. This is really ridiculous. Here is the updated code:
#Bean
public ReactiveAuthenticationManager reactiveAuthenticationManager() {
return authentication -> userService.loginUser(authentication)
.switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication.getName())))
.map(user -> new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities()));
}
I've also simplified the config by removing authenticationSuccessHandler and authenticationManager from the config. Spring automatically redirects to /. For authenticationManager it automatically checks for a ReactiveAuthenticationManager bean and uses if found. Here is my updated config:
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http
.csrf().disable()
.authorizeExchange()
.pathMatchers("/user/account")
.authenticated()
.anyExchange().permitAll()
.and()
.formLogin()
.loginPage("/user/login")
.and()
.logout()
.logoutUrl("/user/logout")
.logoutSuccessHandler(logoutSuccessHandler("/user/bye"))
.and()
.build();
}

Should the OAuth2 Token Endpoint require authentication?

I'm using Spring Security OAuth2 to create my own authorization server. In my case I want to enable a Angular client (SPA) to use the Authorization Code Grant.
The client can use the oauth/authorize endpoint, the user can log in and the browser is redirect to the SPA. Now the client wants to get the token via oauth/token. But this endpoint is secured and needs client id and client secret. The security is enabled by default in Spring.
In the docs I could find the following:
The token endpoint is protected for you by default by Spring OAuth in the #Configuration support using HTTP Basic authentication of the client secret. This is not the case in XML (so it should be protected explicitly).
As far as I know there shouldn't be a client secret used in public clients. But that means, that the oauth/token endpoint should not be secure.
Question: Is it a good practice to disable auth for oauth/token? If not, how should I solve this?
This is my WebSecurityConfig:
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
protected UserDetailsService userDetailsService() {
// WARN: Do not use the default password encoder in production environments!
return new InMemoryUserDetailsManager(
User.withDefaultPasswordEncoder()
.username("user-a")
.password("password")
.roles("USER_ROLE")
.build()
);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http = http
.requiresChannel()
.anyRequest()
.requiresSecure()
.and()
.cors()
.and()
.authorizeRequests()
.antMatchers("/.well-known/**")
.permitAll()
.and();
super.configure(http);
}
#Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(singletonList("*"));
configuration.setAllowedMethods(asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}

Keycloak with vaadin and spring security

I want to secure my vaadin application with keycloak and spring security. I try to use the "keycloak-spring-security-adapter".
My problem is that I want also unauthenticated users to use my application, but with less functionality - I do this with method security and checking which roles the current user has in the UI.
Can I configure the filter so that it ignores unauthenticated requests, but If the token is present uses it?
Thanks
Daniel
A working example of what you want can be found in the public-access branch of this github project. It does use Vaadin 8 though.
In essence, you can setup your application to be partially public, i.e. accessibly to unauthenticated user for certain parts and requires login for others, as follows:
#Configuration
#EnableWebSecurity
#EnableVaadinSharedSecurity
#EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class SecurityConfiguration extends KeycloakWebSecurityConfigurerAdapter {
...
#Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().disable();
http.formLogin().disable();
http.csrf().disable();
http
.authorizeRequests()
.antMatchers("/vaadinServlet/UIDL/**").permitAll()
.antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll()
.anyRequest().permitAll();
http
.logout()
.addLogoutHandler(keycloakLogoutHandler())
.logoutUrl("/sso/logout").permitAll()
.logoutSuccessUrl("/");
http
.addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), BasicAuthenticationFilter.class);
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint());
http
.sessionManagement()
.sessionAuthenticationStrategy(sessionAuthenticationStrategy());
}
...
}
The line http.anyRequest().permitAll(); is the most important where you configure the filter to just allow all requests. You could still update this to only allow public access to certain urls.
You can then use spring security annotations on methods/views/components to configure your fine-grained access control. E.g:
#SpringComponent
#Secured("ROLE_ANONYMOUS")
public class LoginOperation implements Runnable {
#Override
public void run() {
// login logic
}
}
and
#Secured("ROLE_USER")
public class LogoutOperation implements Runnable {
#Override
public void run() {
// logout logic
}
}

Spring Security exclude URL on custom filter

#SuppressWarnings("SpringJavaAutowiringInspection")
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
public void configureAuthentication(AuthenticationManagerBuilder
authenticationManagerBuilder) throws Exception {
authenticationManagerBuilder.userDetailsService(userDetailsService);
}
#Bean
public JwtAuthenticationTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtAuthenticationTokenFilter();
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/test").permitAll()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
httpSecurity.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
}
}
I have a custom filter that runs before Spring Security. I want to be able to exclude some URLs (like /test) from the filter and Spring Security and others to be intercepted (like /api/**).
When using postman to test localhost/test it still goes through the filter even though I have antMatchers("/test").permitAll().
How do I bypass the filter?
You can disable the Spring Security filter chain for some URLs, see WebSecurity#ignoring:
Allows adding RequestMatcher instances that should that Spring Security should ignore. Web Security provided by Spring Security (including the SecurityContext) will not be available on HttpServletRequest that match. Typically the requests that are registered should be that of only static resources. For requests that are dynamic, consider mapping the request to allow all users instead.
Example Usage:
webSecurityBuilder.ignoring()
// ignore all URLs that start with /resources/ or /static/
.antMatchers("/resources/**", "/static/**");
Therefore, you can override WebSecurityConfigurerAdapter#configure:
Override this method to configure WebSecurity. For example, if you wish to ignore certain requests.
To ignore path /test you have to add following method to your configuration:
public void configure​(WebSecurity web)
webSecurityBuilder
.ignoring()
.antMatchers("/test");
}

Disable Basic Authentication while using Spring Security Java configuration

I am trying to secure a web application using Spring Security java configuration.
This is how the configuration looks:-
#Configuration
#EnableWebMvcSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
private String googleClientSecret;
#Autowired
private CustomUserService customUserService;
/*
* (non-Javadoc)
*
* #see org.springframework.security.config.annotation.web.configuration.
* WebSecurityConfigurerAdapter
* #configure(org.springframework.security.config
* .annotation.web.builders.HttpSecurity)
*/
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/","/static/**", "/resources/**","/resources/public/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic().disable()
.requiresChannel().anyRequest().requiresSecure();
// #formatter:on
super.configure(http);
}
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
// #formatter:off
auth
.eraseCredentials(true)
.userDetailsService(customUserService);
// #formatter:on
super.configure(auth);
}
}
Notice that I have explicitly disabled HTTP Basic authentication using:-
.httpBasic().disable()
I am still getting HTTP Authenticaton prompt box while accessing a secured url. Why?
Please help me fix this.
I just want to render the default login form that comes bundled.
Spring Boot Starter Version : 1.1.5
Spring Security Version : 3.2.5
Thanks
First of all, calling super.configure(http); will override whole your configuration you have before that.
Try this instead:
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.httpBasic().disable();
In case you use Spring Boot, the documentation states:
To switch off the Boot default configuration completely in a web
application you can add a bean with #EnableWebSecurity
So if you want to fully customize itself that might be an option.
Just to make it clear... You just need to put #EnableWebSecurity annotation on your main application class or application configuration class.
You can disable the formLogin through the HttpSecurity instance as follow:
http.authorizeRequests().antMatchers("/public/**").permitAll()
.antMatchers("/api/**").hasRole("USER")
.anyRequest().authenticated()
.and().formLogin().disable();
This will lead receiving 403 Http error when trying to access any secured resource
Anonymous option worked for me. My code like
http.csrf().disable().headers().frameOptions().sameOrigin().and().
authorizeRequests().anyRequest().anonymous().and().httpBasic().disable();
Suitable for Spring Boot or folks using OAuth
#Profile("test")
#EnableWebSecurity
static class BasicWebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().anonymous().and().httpBasic().disable();
}
}
If you are using #EnableOAuth2Client or #EnableResourceServer, then in test profile switch to basic auth and then disable the same. In Spring Boot,to switch off the spring security default configuration completely in a web application you need to add a bean with #EnableWebSecurity
The following worked for me:
http
.authorizeRequests()
.anyRequest().permitAll();

Resources