Project

General

Profile

Download (8.16 KB) Statistics
| Branch: | Tag: | Revision:
1
/**
2
 * Copyright (C) 2016 EDIT
3
 * European Distributed Institute of Taxonomy
4
 * http://www.e-taxonomy.eu
5
 *
6
 * The contents of this file are subject to the Mozilla Public License Version 1.1
7
 * See LICENSE.TXT at the top of this package for the full license terms.
8
 */
9
package eu.etaxonomy.cdm.remote.config;
10

    
11
import org.apache.log4j.Logger;
12
import org.springframework.beans.factory.annotation.Autowired;
13
import org.springframework.context.annotation.Bean;
14
import org.springframework.context.annotation.Configuration;
15
import org.springframework.context.annotation.Lazy;
16
import org.springframework.context.annotation.Scope;
17
import org.springframework.context.annotation.ScopedProxyMode;
18
import org.springframework.http.HttpMethod;
19
import org.springframework.security.authentication.AuthenticationManager;
20
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
21
import org.springframework.security.config.http.SessionCreationPolicy;
22
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
23
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
24
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
25
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
26
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
27
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
28
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
29
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
30
import org.springframework.security.oauth2.provider.ClientDetailsService;
31
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
32
import org.springframework.security.oauth2.provider.approval.InMemoryApprovalStore;
33
import org.springframework.security.oauth2.provider.approval.UserApprovalHandler;
34
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
35
import org.springframework.security.oauth2.provider.token.TokenStore;
36
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
37

    
38
import eu.etaxonomy.cdm.remote.oauth2.CdmUserApprovalHandler;
39

    
40
@Configuration
41
public class OAuth2ServerConfiguration {
42

    
43
    private static final String CDM_RESOURCE_ID = "cdm";
44

    
45
    private static final String ACCEXPR_MANAGE_CLIENT =
46
            "#oauth2.clientHasRole('ROLE_CLIENT') "
47
          + "or (!#oauth2.isOAuth() and ( "
48
          + "      hasRole('ROLE_ADMIN') or hasRole('" + MultiWebSecurityConfiguration.ROLE_MANAGE_CLIENT + "')"
49
          + "   )"
50
          + ")";
51

    
52
    @EnableResourceServer
53
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
54

    
55
        @Override
56
        public void configure(ResourceServerSecurityConfigurer resources) {
57
            resources.resourceId(CDM_RESOURCE_ID).stateless(false);
58
        }
59

    
60
        @Override
61
        public void configure(HttpSecurity http) throws Exception {
62
            // @formatter:off
63
            http
64
                // Since we want the protected resources to be accessible in the UI as well we need
65
                // session creation to be allowed (it's disabled by default in 2.0.6)
66
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
67
            .and()
68
                .authorizeRequests()
69
                    // see
70
                    // - http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#el-access
71
                    //      or
72
                    //   org.springframework.security.access.expression.SecurityExpressionRoot
73
                    // - org.springframework.security.oauth2.provider.expression.OAuth2SecurityExpressionMethods
74
                    .antMatchers(HttpMethod.OPTIONS, "/manage/**").permitAll() // see #6393
75
                    .antMatchers("/manage/**").access(ACCEXPR_MANAGE_CLIENT)
76
                    .antMatchers("/**description/accumulateDistributions").access(ACCEXPR_MANAGE_CLIENT)
77
                    .antMatchers("/user/me").access("isAuthenticated()")
78
                    .regexMatchers("/user/.*|/user\\..*").access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER_MANAGER')")
79

    
80
                    // ------ DELVELOPER SNIPPETS ------
81
                    // experiments with classification controller
82
                    //.regexMatchers("/classification/.*|/classification\\..*")
83
                            //.access("#oauth2.hasScope('trust')")
84
                            //.access("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")
85
                            //.access("#oauth2.clientHasRole('ROLE_CLIENT') or (!#oauth2.isOAuth() and hasAnyRole('ROLE_ADMIN', 'ROLE_USER'))")
86
                    //
87
                    // .regexMatchers(HttpMethod.DELETE, "/oauth/users/([^/].*?)/tokens/.*")
88
                    //     .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('write')")
89
                    // .regexMatchers(HttpMethod.GET, "/oauth/clients/([^/].*?)/users/.*")
90
                    //     .access("#oauth2.clientHasRole('ROLE_CLIENT') and (hasRole('ROLE_USER') or #oauth2.isClient()) and #oauth2.hasScope('read')")
91
                    // .regexMatchers(HttpMethod.GET, "/oauth/clients/.*")
92
                    //     .access("#oauth2.clientHasRole('ROLE_CLIENT') and #oauth2.isClient() and #oauth2.hasScope('read')");
93
                    // ---------------------------
94
            .and().httpBasic();
95
            // @formatter:on
96
        }
97

    
98
    }
99

    
100
    /**
101
     * @author a.kohlbecker
102
     * @since Oct 6, 2016
103
     *
104
     */
105
    @Configuration
106
    @EnableAuthorizationServer
107
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
108

    
109
        private static final String CLIENT_ID = "any-client";
110

    
111
        public static final Logger logger = Logger.getLogger(AuthorizationServerConfiguration.class);
112

    
113
        @Autowired
114
        private UserApprovalHandler userApprovalHandler;
115

    
116
        @Autowired
117
        @Lazy // avoid dependency cycle coming from UserService.authenticationManager
118
        private AuthenticationManager authenticationManager;
119

    
120
        @Bean
121
        public TokenStore tokenStore() {
122
            return new InMemoryTokenStore();
123
        }
124

    
125

    
126
        @Override
127
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
128

    
129
            InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
130

    
131
            // @formatter:off
132
            /*
133
             * Client for 'implicit grant'
134
             */
135
            builder.withClient(CLIENT_ID)
136
            //.resourceIds(RESOURCE_ID)
137
            .authorizedGrantTypes("authorization_code", "refresh_token", "implicit")
138
            .authorities("ROLE_CLIENT")
139
            .scopes("read", "write", "trust")
140
            .secret("secret") // secret for login of the client into /oauth/token
141
            .autoApprove("read");
142
            // @formatter:on
143

    
144
        }
145

    
146

    
147
        @Override
148
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
149
            endpoints.tokenStore(tokenStore()).userApprovalHandler(userApprovalHandler)
150
                    .authenticationManager(authenticationManager);
151
        }
152

    
153
    }
154

    
155

    
156
   protected static class CommonBeans {
157

    
158
        @Autowired
159
        private ClientDetailsService clientDetailsService;
160

    
161

    
162
        @Bean
163
        public ApprovalStore approvalStore() {
164
            return new InMemoryApprovalStore();
165
        }
166

    
167
        @Bean
168
        @Lazy
169
        @Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
170
        public CdmUserApprovalHandler userApprovalHandler() throws Exception {
171
            CdmUserApprovalHandler handler = new CdmUserApprovalHandler();
172
            handler.setApprovalStore(approvalStore());
173
            handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
174
            handler.setClientDetailsService(clientDetailsService);
175
            handler.setUseApprovalStore(false);
176
            return handler;
177
        }
178
    }
179
}
(4-4/5)