Projekt

Obecné

Profil

Stáhnout (5.84 KB) Statistiky
| Větev: | Tag: | Revize:
1
package cz.zcu.kiv.backendapi.security;
2

    
3
import cz.zcu.kiv.backendapi.security.jwt.JwtTokenVerifier;
4
import cz.zcu.kiv.backendapi.security.jwt.JwtUsernameAndPasswordAuthenticationFilter;
5
import cz.zcu.kiv.backendapi.security.jwt.JwtUtils;
6
import cz.zcu.kiv.backendapi.user.Role;
7
import cz.zcu.kiv.backendapi.user.permission.Permission;
8
import lombok.RequiredArgsConstructor;
9
import org.springframework.context.annotation.Bean;
10
import org.springframework.context.annotation.Configuration;
11
import org.springframework.http.HttpMethod;
12
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
13
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
14
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
15
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
16
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
17
import org.springframework.security.config.http.SessionCreationPolicy;
18
import org.springframework.security.core.userdetails.UserDetailsService;
19
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
20
import org.springframework.web.cors.CorsConfiguration;
21
import org.springframework.web.cors.CorsConfigurationSource;
22
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
23

    
24
import java.util.Arrays;
25
import java.util.Collections;
26
import java.util.HashMap;
27
import java.util.Map;
28

    
29
/**
30
 * Security config class
31
 */
32
@Configuration
33
@EnableWebSecurity
34
@RequiredArgsConstructor
35
public class SecurityConfig extends WebSecurityConfigurerAdapter {
36

    
37
    /**
38
     * Map of permitted endpoints with HTTP method (user does not need to be authenticated perform the request)
39
     */
40
    private static final Map<String, HttpMethod> PERMITTED_ENDPOINTS;
41

    
42
    /**
43
     * User detail service
44
     */
45
    private final UserDetailsService userDetailsService;
46

    
47
    /**
48
     * Password encoder
49
     */
50
    private final BCryptPasswordEncoder bCryptPasswordEncoder;
51

    
52
    /**
53
     * JWT utils
54
     */
55
    private final JwtUtils jwtUtils;
56

    
57
    static {
58
        PERMITTED_ENDPOINTS = new HashMap<>();
59
        PERMITTED_ENDPOINTS.put("/login", HttpMethod.POST);
60
        PERMITTED_ENDPOINTS.put("/users/token", HttpMethod.GET);
61
        PERMITTED_ENDPOINTS.put("/swagger-ui/**", HttpMethod.GET);
62
        PERMITTED_ENDPOINTS.put("/swagger-ui.html", HttpMethod.GET);
63
        PERMITTED_ENDPOINTS.put("/v3/api-docs", HttpMethod.GET);
64
        PERMITTED_ENDPOINTS.put("/v3/api-docs/swagger-config", HttpMethod.GET);
65
        PERMITTED_ENDPOINTS.put("/catalog-items", HttpMethod.GET);
66
        PERMITTED_ENDPOINTS.put("/catalog-items/**", HttpMethod.GET);
67
        PERMITTED_ENDPOINTS.put("/title-page", HttpMethod.GET);
68
    }
69

    
70
    /**
71
     * Security configuration
72
     *
73
     * @param http http security
74
     * @throws Exception exception
75
     */
76
    // TODO configure and check rights
77
    @Override
78
    protected void configure(HttpSecurity http) throws Exception {
79
        http.csrf().disable()
80
                .cors()
81
                .and()
82
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
83
                .and()
84
                .addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtUtils))
85
                .addFilterAfter(new JwtTokenVerifier(jwtUtils, PERMITTED_ENDPOINTS), JwtUsernameAndPasswordAuthenticationFilter.class)
86
                .authorizeRequests()
87
                .antMatchers(HttpMethod.GET, PERMITTED_ENDPOINTS.keySet().stream().filter(k -> PERMITTED_ENDPOINTS.get(k).equals(HttpMethod.GET)).toArray(String[]::new)).permitAll()
88
                .antMatchers(HttpMethod.POST, "/login").permitAll()
89
                .antMatchers("/external-catalog-items").hasRole(Role.ADMIN.name())
90
                .antMatchers(HttpMethod.PATCH, "/users/*/permissions", "/users/*/password").hasRole(Role.ADMIN.name())
91
                .antMatchers(HttpMethod.DELETE, "/users/**").hasRole(Role.ADMIN.name())
92
                .antMatchers(HttpMethod.GET, "/users").hasRole(Role.ADMIN.name())
93
                .antMatchers(HttpMethod.GET, "/path").hasAuthority(Permission.READ.name())
94
                .antMatchers(HttpMethod.POST, "/catalog-items").hasAuthority(Permission.WRITE.name())
95
                .antMatchers(HttpMethod.PUT, "/catalog-items/*").hasAuthority(Permission.WRITE.name())
96
                .antMatchers(HttpMethod.DELETE, "/catalog-items/*").hasAuthority(Permission.DELETE.name())
97
                .antMatchers(HttpMethod.POST, "/title-page").hasRole(Role.ADMIN.name())
98
                .anyRequest()
99
                .authenticated();
100
    }
101

    
102
    /**
103
     * Sets authentication provider to authentication manager
104
     *
105
     * @param auth authentication manager builder
106
     */
107
    @Override
108
    protected void configure(final AuthenticationManagerBuilder auth) {
109
        auth.authenticationProvider(authenticationProvider());
110
    }
111

    
112

    
113
    /**
114
     * Returns authentication provider
115
     *
116
     * @return authentication provider
117
     */
118
    @Bean
119
    public DaoAuthenticationProvider authenticationProvider() {
120
        final DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
121
        provider.setUserDetailsService(userDetailsService);
122
        provider.setPasswordEncoder(bCryptPasswordEncoder);
123
        return provider;
124
    }
125

    
126
    @Bean
127
    CorsConfigurationSource corsConfigurationSource() {
128
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
129
        CorsConfiguration corsConfiguration = new CorsConfiguration().applyPermitDefaultValues();
130
        corsConfiguration.setAllowedMethods(java.util.List.of(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name(), HttpMethod.DELETE.name(), HttpMethod.PATCH.name(), HttpMethod.PUT.name()));
131
        source.registerCorsConfiguration("/**", corsConfiguration);
132
        return source;
133
    }
134
}
(2-2/2)