Project

General

Profile

1
package eu.dnetlib.organizations;
2

    
3
import javax.sql.DataSource;
4

    
5
import org.springframework.beans.factory.annotation.Autowired;
6
import org.springframework.context.annotation.Bean;
7
import org.springframework.context.annotation.Configuration;
8
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
9
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
11
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
12
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
13
import org.springframework.security.crypto.password.PasswordEncoder;
14
import org.springframework.security.web.access.AccessDeniedHandler;
15

    
16
import eu.dnetlib.organizations.controller.UserRole;
17

    
18
@Configuration
19
@EnableWebSecurity
20
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
21

    
22
	@Autowired
23
	private DataSource dataSource;
24

    
25
	@Autowired
26
	private AccessDeniedHandler accessDeniedHandler;
27

    
28
	@Override
29
	protected void configure(final HttpSecurity http) throws Exception {
30

    
31
		http.csrf()
32
				.disable()
33
				.authorizeRequests()
34
				.antMatchers("/", "/api/**")
35
				.hasAnyRole(UserRole.ADMIN.name(), UserRole.NATIONAL_ADMIN.name(), UserRole.USER.name())
36
				.antMatchers("/registration_api/**")
37
				.hasRole(UserRole.NOT_AUTHORIZED.name())
38
				.antMatchers("/resources/**", "/webjars/**")
39
				.permitAll()
40
				.anyRequest()
41
				.authenticated()
42
				.and()
43
				.formLogin()
44
				.loginPage("/login")
45
				.permitAll()
46
				.and()
47
				.logout()
48
				.permitAll()
49
				.and()
50
				.exceptionHandling()
51
				.accessDeniedHandler(accessDeniedHandler);
52
	}
53

    
54
	@Autowired
55
	public void configureGlobal(final AuthenticationManagerBuilder auth) throws Exception {
56
		auth.jdbcAuthentication()
57
				.dataSource(dataSource)
58
				.usersByUsernameQuery("select ?, '{MD5}60c4a0eb167dd41e915a885f582414df', true")  // TODO: this is a MOCK, the user should
59
																								  // be authenticated using the openaire
60
																								  // credentials
61
				.authoritiesByUsernameQuery("with const as (SELECT ? as email) "
62
						+ "select c.email, 'ROLE_'||coalesce(u.role, '"
63
						+ UserRole.NOT_AUTHORIZED
64
						+ "') from const c left outer join users u on (u.email = c.email)");
65
	}
66

    
67
	@Bean
68
	public PasswordEncoder passwordEncoder() {
69
		return PasswordEncoderFactories.createDelegatingPasswordEncoder();
70
	}
71

    
72
}
(3-3/3)