SpringBoot+REST+Security - either all access open or all closed - spring

What I am trying to do should be pretty easy:
a REST-Service with 3 different security levels:
A "public" RestService accessible by all
A "protected" RestService for "USER"s
A "private" RestService for "ADMIN"s
but either I have Access to all - or with the current config I got acces to NONE, because Without BasicAuth I always got
Full authentication is required to access this resource
and with the "uuu" + "ppp" I always got
Bad credentials
By the way I using spring boot 1.5.3
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
#Configuration
#EnableWebSecurity
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("aaa").password("ppp").roles("USER", "ADMIN");
auth.inMemoryAuthentication().withUser("uuu").password("ppp").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.antMatchers("/protected/**").hasRole("USER")
.antMatchers("/private/**").hasRole("ADMIN")
.and().httpBasic()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); // We don't need sessions to be created.
}
#Override
public void configure(WebSecurity web) throws Exception {
web
.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**"); /* To allow Pre-flight [OPTIONS] request from browser */
}
}

The OP found their solution actually works. There was a problem with the component-Scan, because my Rest project is a child of my DAO and Repository-Project...
#SpringBootApplication
#EnableAutoConfiguration
#ComponentScan({"com.leycarno.base", "com.leycarno.rest"}) // now we're listen to all the nice components :-)
#EnableJpaRepositories("com.leycarno.base.repositories")
#EntityScan("com.leycarno.base.models")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

Related

Spring security Azure active directory

Could you please suggest how to increase the timeout. I am getting below exception and this is not coming every time. I have Angular 5 as front end and in back end using Spring Boot 2.0.4 and azure active directory release 2.0.5 (latest).
com.nimbusds.jose.RemoteKeySourceException: Couldn't retrieve remote JWK set: Read timed out.Below is my source code.
Thank in advance.
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.microsoft.azure.spring.autoconfigure.aad.AADAuthenticationFilter;
#EnableWebSecurity
#EnableGlobalMethodSecurity(securedEnabled = true,prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AADAuthenticationFilter aadAuthFilter;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/api/ppo/dashboard/dashboardstats").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/dashboard/castats").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/authenticate/privileges").permitAll();
http.authorizeRequests().antMatchers("/api/ppo/**").authenticated();
//http.authorizeRequests().antMatchers("/api/ppo/autenticate/**").permitAll();
http.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/").deleteCookies("JSESSIONID").invalidateHttpSession(true);
//http.authorizeRequests().anyRequest().permitAll();
http.csrf().disable();
http.cors();
// http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
http.addFilterBefore(aadAuthFilter, UsernamePasswordAuthenticationFilter.class);
}
#Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/ppo/**").allowedMethods("GET", "POST", "PUT", "DELETE").allowedOrigins("*")
.allowedHeaders("*");
}
};
}

Spring boot Security URL Configuration

I have set the root path as:-
server.contextPath=/myspringBootApp (in Application.propertes) file.
and changed the configuration file as:-
package com.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public CustomAuthenticationEntryPoint unauthorizedHandler;
#Autowired
MyDaoAuthenticationProvider authProvider;
#Bean
public CustomAuthenticationTokenFilter authenticationTokenFilterBean() {
return new CustomAuthenticationTokenFilter();
}
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider.authProvider());
}
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.csrf().disable()
.authorizeRequests()
// UI related urls
.antMatchers(
HttpMethod.GET,
"/",
"/myspringBootApp/login",
"/content/**",
"/*.html",
"/favicon.ico",
"/**/*.html",
"/**/*.css",
"/**/*.js",
"/assets/**"
).permitAll()
//Back end - auth layer
.antMatchers("/auth/user").permitAll()
//Back end - actual rest layer
.antMatchers(HttpMethod.POST,"/auth/login").permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler);
httpSecurity.addFilterBefore(authenticationTokenFilterBean(),UsernamePasswordAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
The above code is not working and loading the UI. I tried changing the UI URLs to /myspringBootApp/favicon.ico, but this also dint give desired result.
Can anyone help me to find a solution?
I think you can use the WebSecurity part of the WebSecurityConfigurerAdapter for this:
#Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/")
.antMatchers("/favicon.ico")
.antMatchers("/**.css")
.antMatchers("/webjars/**")
...

Spring Boot doesn't seem to see my web security config

This is my first time with a Spring Boot secured REST app. I've added spring-boot-starter-security to my classpath, and I understand that automatically secures all URLs. But at this point in my development, I'm not ready to do that, so I added an antMatcher to ALLOW all URLs. But no matter what I put in my WebSecurityConfig, I still get an the error message:
Full authentication is required to access this resource
Below is my WebSecurityConfig in full. Is there something else I need to do for Spring to pick this up? How can verify if it's being used at all? Many thanks!
package com.company.jwt.security;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import com.company.jwt.UserUtils;
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/**").permitAll();
}
#Override
protected void configure(AuthenticationManagerBuilder authBuilder) throws Exception {
authBuilder.userDetailsService(inMemoryUserDetailsManager());
}
#Bean
public InMemoryUserDetailsManager inMemoryUserDetailsManager() {
Properties props = new Properties();
UserUtils.getUsers()
.forEach(e -> props.put(e.getUsername(), e.getPassword() + "," +
e.getAuthorities() + ", enabled"));
return new InMemoryUserDetailsManager(props);
}
}
What kind of URL are you trying to access there? A rest controller that you created?
There may be something overriding the permission of your URLs.
I ran the code bellow with no problem (SpringBoot 1.5.2).
#SpringBootApplication
#RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#RequestMapping("/foo")
public String foo() {
return "foo";
}
}
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/**").permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
$ curl -s http://localhost:8080/foo
foo

Spring Oauth2 not working for me - Status Not Answered

I am trying out Oauth2 with Spring security. I am trying to call the /getresource service in my resource class by following the below
GET http://localhost:8080/oauth/authorize?
response_type=code
&client_id=my-first-client
&redirect_url=http://localhost:8080/getcode
&scope=read
Get the code and call the Authorization service to get the auth token by doing
POST http://localhost:8080/oauth/token
grant_type=authorization_code&code=XXXX
Get the token and call the /getresource rest service.
by
GET http://localhost:8080/getresource
Header : Authorization: Bearer <>
But I have been getting the below error
<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>
Any help will to locate the issue will be greatly appreciated.
My Authorization class
package auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
#EnableAuthorizationServer
#SpringBootApplication
#EnableWebSecurity
public class AuthProvider extends WebSecurityConfigurerAdapter implements AuthorizationServerConfigurer{
#Autowired
AuthenticationManager authenticationManager;
#Autowired
DriverManagerDataSource dataSource;
public static void main(String[] args)
{
SpringApplication.run(AuthProvider.class, args);
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
String uname_query = "select username,userpass,enabled from users where username=?";
String role_query = "Select username, role_name from user_roles where username=?";
auth.jdbcAuthentication().dataSource(dataSource)
.usersByUsernameQuery(uname_query)
.authoritiesByUsernameQuery(role_query);
}
/* #Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login","/home","/403","/oauth/**","/resources/**").permitAll()
.antMatchers("/getresource").access("#oauth2.hasScope('read')")
.anyRequest().authenticated().and().formLogin().loginPage("/login");
}*/
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// TODO Auto-generated method stub
security.allowFormAuthenticationForClients();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("my-first-client")
.secret("password")
.accessTokenValiditySeconds(120)
.authorizedGrantTypes("authorization_code", "refresh_token","password")
.authorities("ROLE_CLIENT")
.redirectUris("http://localhost:8080/authcode")
.resourceIds("testresource");
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// TODO Auto-generated method stub
endpoints.authenticationManager(authenticationManager);
}
}
My Resource class
package auth;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#EnableResourceServer
#RestController
public class Resource {
private static final String resourceid="testresource";
#RequestMapping("/getresource")
public String getResource()
{
return "Hello Everyone!!";
}
private static class Resourceconfigurator extends ResourceServerConfigurerAdapter
{
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(Resource.resourceid);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login","/home","/403","/oauth/**","/resources/**").permitAll()
.antMatchers("/getresource").access("#oauth2.hasScope('read')")
.anyRequest().authenticated().and().formLogin().loginPage("/login");
}
}
}

"could not obtain access token" error in spring security oauth2

In my spring project i have an oauth2 client app running on localhost:9999 and an oauth2 authorization server running on localhost:8080.
In result, after approval page, i see error page that i don't know what is the problem?
when press F12 i see that set-cookie done! but /oauth/token not called! and /me also not called! and browser not redirect to localhost:9999.
my client app
package sso.client;
import java.security.Principal;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#EnableAutoConfiguration
#Configuration
#EnableOAuth2Sso
#RestController
public class App {
#RequestMapping("/")
public String home(Principal user) {
return "Hello " + user.getName();
}
public static void main(String[] args) {
new SpringApplicationBuilder(App.class)
.properties("spring.config.name=client").run(args);
}
}
client.yml
server:
port: 9999
security:
oauth2:
client:
client-id: acme
client-secret: acmesecret
access-token-uri: http://localhost:8080/oauth/token
user-authorization-uri: http://localhost:8080/oauth/authorize
resource:
user-info-uri: http://localhost:8080/me
my authorization server
package sso.raymon;
import java.security.Principal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#Configuration
#EnableAutoConfiguration
#RestController
#EnableWebSecurity
public class App extends WebSecurityConfigurerAdapter
{
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
#Configuration
#EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter{
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security)
throws Exception {
// TODO Auto-generated method stub
security.allowFormAuthenticationForClients();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// #formatter:off
clients.inMemory()
.withClient("acme")
.authorizedGrantTypes("authorization_code")
.authorities("ROLE_CLIENT")
.scopes("read", "write")
.secret("acmesecret");
// #formatter:on
}
}
#RequestMapping("/me")
public String home(Principal user) {
return user.getName();
}
#Configuration
#EnableResourceServer
protected static class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/me")
.authorizeRequests().anyRequest().authenticated();
}
}
}
application.properties
security.user.name=forough
security.user.password=m123
Error in blow URL:
localhost:9999/login?code=xZgYwZ&state=27XzVY
Error:
Whitelable Error Page
this application has no explicit mapping for /error, so you are seeing this a fallback.
There was an unexpected erroe (type=Unauthorized, atatus=401).
Authentication Failed: could not obtain access token

Resources