Authorisation and role check in a spring boot application - spring-boot

I have a spring boot application where I have several REST APIs. Now I want to do a authorisation check for all the requests. This involves each request using a x509 client certificate and then some business logic for authorisation purpose, something similar to role checking.
what is the best place to do this i.e. should this check be done in DispatcherServlet - doDispatch method? Doing the same check for each request in Controller doesn't make much of a sense.
Can someone suggest where to put these kind of checks in a spring boot application ?

You have two choices. Java config or xml config.
I recommend java config. Create a config class and configure like this
For java config it would look something like
#Configuration
#EnableWebSecurity
public class LoginSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication()
.withUser("jduser").password("jdu#123").authorities("ROLE_USER")
.and()
.withUser("jdadmin").password("jda#123").authorities("ROLE_USER","ROLE_ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/userPage").access("hasRole('ROLE_USER')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("username").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
}

Related

How to support basic authentication and bearer authentication for the REST API project

I am new to Spring Security & still learning it so my question can be naive please bear with it.
I have Sprint Boot Rest API project which exposes certain APIs. I have already implemented the bearer token based authentication for all the APIs.
e.g /user , /resource, /appointment
Now for few apis for a particular controller I would like to have the basic authentication implemented. These Apis will be consumed by another service which is not exposed to public.
In order to have the security for the APIs I would like to have basic authentication in place for these apis.
e.g /internal/api1 , internal/api2 .. and so on
I am not able to distinguished between urls in the ResourceServerConfigurerAdapter & WebSecurityConfigurerAdapter. Also not sure which should be used for adding basicAuth() using the antmatchers
What you want, by reading your problem, is to have two authentication types (token and httpBasic) for two diffetent endpoints. It can be achieved by creating two different WebSecurityConfigurerAdapter beans. Spring Boot enables this and can be done like bellow:
#Order(1) - /resource|user|appointment/** protected by bearer token authentication.
#Order(2) - /internal/** protected by basic auth.
View docs for Spring Boot and sample code here.
#EnableWebSecurity
public class SecurityConfig {
#Configuration
#Order(1)
public class ApiSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/resource/**")
.antMatcher("/user/**")
.antMatcher("/appointment/**")
.authorizeRequests()
.anyRequest().authenticated()
.and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilterBefore(jwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
#Configuration
#Order(2)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/internal/**")
.and()
.httpBasic();
}
}
}

How do you include Spring Boot Actuator with SB 2.1 and not have all endpoints locked under security

I literally can't figure this out and have been through a dozen answers and none of them work. What exactly is the configuration to stop the redirect to login? I'd prefer to leave my actuator endpoints behind security but I honestly don't care either way at this point because I need this application to be usable.
There’s an example of the configuration that is required in Spring Boot’s reference documentation:
#Configuration
public class ActuatorSecurity extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requestMatcher(EndpointRequest.toAnyEndpoint())
.authorizeRequests()
.anyRequest().permitAll();
}
}
Security configuration for a Spring Webflux service to allow access to actuator endpoints:
#Configuration
public class SecurityConfig {
#Bean
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
return http.authorizeExchange()
// .pathMatchers("/actuator/**").permitAll()
.anyExchange().permitAll()
.and().csrf().disable().build();
}
}

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();
}
}

Spring Security custom filter chain proxy using java config for mvc application

We are trying to use Spring Security in a Spring Boot application and would like to use the java config to configure spring security.
On top of this we would like to use our own filters to modify some behaviour before and after logging in.
Something similar to http://sleeplessinslc.blogspot.in/2012/02/spring-security-stateless-cookie-based.html
Does anyone have any idea how to create the SecurityConfig.java where we can customize the filter sequence and add our own filters to it.
Have tried http://shazsterblog.blogspot.com/2014/07/spring-security-custom-filterchainproxy.html but didn't get it to point to the my login page.
You can add CustomUsernamePasswordAuthenticationFilterto the securityCOnfig.java
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Bean
public CustomUsernamePasswordAuthenticationFilter customUsernamePasswordAuthenticationFilter()
throws Exception {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().antMatchers("/*").permitAll()
.anyRequest().hasRole("USER").and()
.formLogin()
.permitAll();
http.addFilterBefore(new CustomFilter(), LogoutFilter.class);
//.and().anonymous().disable();
}
Here is a similar post - Spring security custom authentication filter without web.xml
Here are two tutorials - http://www.journaldev.com/2715/spring-security-in-servlet-web-application-using-dao-jdbc-in-memory-authentication

Securing a REST application in SpringBoot and accessing it from a Rest Client

I am pretty new to Springboot. I have developed a rest server but I was wondering how to perform Basic authentication from a client and how to configure the spring boot server to authenticate request. The tutorials I saw online didn't include a restful client. Would be great if you can show some code including both the client request and server authentication process with springboot rest.
On the client side since you are using Jersey Client you need to do something like the following:
Client c = Client.create();
c.addFilter(new HTTPBasicAuthFilter(user, password));
One the server side you need to enable Spring Security and set Basic Authentication for it which would look something like the following (this is the simplest possible case).
#Configuration
#EnableWebSecurity
public class RootConfig extends WebSecurityConfigurerAdapter {
#Override
protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("tester").password("passwd").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeUrls()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}

Resources