Project

General

Profile

« Previous | Next » 

Revision 59812

[Trunk | Monitor Service]: uoa-authorization-library dependency added:
1. pom.xml: Added dependencies for spring security and for uoa-authorization-library | [Bug fix] spring boot version set to 1.5.8 (it was accidentally set to 1.5.18 and library was not compatible).
2. UoaMonitorServiceApplication.java: Added authorization.properties | Remove SecurityConfig from configuration (done by authorization library) | import AuthorizationConfiguration.
3. ExceptionsHandler.java: Add handler for AccessDeniedException.
4. monitorservice.properties: Remove security properties (and add missing properties for mongodb).
5. UoaMonitorServiceConfiguration.java: Remove interceptor for AuthorizationHandler.
6. SecurityConfig.java & AuthorizationHandler.java & AuthorizationUtils.java: Removed unnecessary files (authorization is done via authorization library).

View differences:

modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/handlers/AuthorizationHandler.java
1
package eu.dnetlib.uoamonitorservice.handlers;
2

  
3
import eu.dnetlib.uoamonitorservice.handlers.utils.AuthorizationUtils;
4
import org.apache.log4j.Logger;
5
import org.springframework.beans.factory.annotation.Value;
6
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
7

  
8
import javax.servlet.http.HttpServletRequest;
9
import javax.servlet.http.HttpServletResponse;
10
import java.util.List;
11

  
12
public class AuthorizationHandler extends HandlerInterceptorAdapter {
13
    private final Logger log = Logger.getLogger(this.getClass());
14
    private AuthorizationUtils helper = new AuthorizationUtils();
15
    private List<String> allowedPostRequests;
16

  
17
    public AuthorizationHandler(String userInfoUrl, String originServer, List<String> allowedPostRequests){
18
        helper.setOriginServer(originServer);
19
        helper.setUserInfoUrl(userInfoUrl);
20
        this.allowedPostRequests = allowedPostRequests;
21
    }
22
// Comment this method ONLY FOR TEST
23
//    @Override
24
//    public boolean preHandle(
25
//            HttpServletRequest request,
26
//            HttpServletResponse response,
27
//            Object handler) throws Exception {
28
////        log.debug("request method " + request.getRemoteHost());
29
//        log.debug("properties: " + helper.getOriginServer() + " "+ helper.getUserInfoUrl());
30
//        log.debug(allowedPostRequests);
31
//        log.debug(allowedPostRequests.contains(request.getServletPath()));
32
//        log.debug(request.getServletPath());
33
//        if((request.getMethod().equals("POST") || request.getMethod().equals("DELETE")) &&
34
//        !allowedPostRequests.contains(request.getServletPath())) {
35
//            //TODO check domain & check user info
36
//            if(!this.helper.checkCookies(request) || !helper.isAuthorized(helper.getToken(request))){
37
//
38
//                response.setHeader("Access-Control-Allow-Credentials","true");
39
//                response.setHeader("Access-Control-Allow-Origin","*");
40
//                response.setHeader("Vary","Origin");
41
//
42
//                response.setStatus(403);
43
//                response.sendError(403, "Forbidden: You don't have permission to access. Maybe you are not registered.");
44
//                return false;
45
//            }
46
//
47
//        }
48
//        return true;
49
//    }
50

  
51

  
52
//    @Override
53
//    public void postHandle(
54
//            HttpServletRequest request,
55
//            HttpServletResponse response,
56
//            Object handler,
57
//            ModelAndView modelAndView) throws Exception {
58
//        log.info("I am here - postHandle ");
59
//    }
60
//
61
//    @Override
62
//    public void afterCompletion(
63
//            HttpServletRequest request,
64
//            HttpServletResponse response,
65
//            Object handler, Exception ex) {
66
//        log.info("I am here - afterCompletion ");
67
//    }
68

  
69
}
modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/handlers/ExceptionsHandler.java
5 5
import org.springframework.data.crossstore.ChangeSetPersister;
6 6
import org.springframework.http.HttpStatus;
7 7
import org.springframework.http.ResponseEntity;
8
import org.springframework.security.access.AccessDeniedException;
8 9
import org.springframework.web.bind.MissingServletRequestParameterException;
9 10
import org.springframework.web.bind.annotation.ControllerAdvice;
10 11
import org.springframework.web.bind.annotation.ExceptionHandler;
11 12
import org.springframework.web.bind.annotation.RestController;
13
import org.springframework.web.multipart.support.MissingServletRequestPartException;
12 14

  
13 15
@ControllerAdvice
14 16
@RestController
......
69 71
        log.error("pathNotValidException exception : "+ ex.getMessage());
70 72
        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.NOT_FOUND);
71 73
    }
74

  
75
    @ExceptionHandler(AccessDeniedException.class)
76
    public ResponseEntity<ExceptionResponse> accessDeniedException(Exception ex) {
77
        ExceptionResponse response = new ExceptionResponse();
78
        response.setErrorCode("Forbidden Exception");
79
        response.setErrorMessage("Access Denied Exception");
80
        response.setErrors(ex.getMessage());
81
        response.setStatus(HttpStatus.FORBIDDEN);
82
        log.error("accessDeniedException exception : "+ ex.getMessage());
83
        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.FORBIDDEN);
84
    }
72 85
}
modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/handlers/utils/AuthorizationUtils.java
1
package eu.dnetlib.uoamonitorservice.handlers.utils;
2

  
3
import org.apache.log4j.Logger;
4

  
5
import javax.servlet.http.Cookie;
6
import javax.servlet.http.HttpServletRequest;
7
import java.io.BufferedReader;
8
import java.io.InputStreamReader;
9
import java.io.StringReader;
10
import java.net.HttpURLConnection;
11
import java.net.URL;
12
import java.util.Enumeration;
13

  
14
import com.google.gson.Gson;
15

  
16
public class AuthorizationUtils {
17
    private final Logger log = Logger.getLogger(this.getClass());
18
    private String userInfoUrl = null;
19
//    private String communityAPI ="";
20
//    List<String> adminRoles = new ArrayList<String>(Arrays.asList("Super Administrator",  "Portal Administrator"));
21
    private String originServer= null;
22
    public Boolean checkCookies(HttpServletRequest request){
23
        Boolean valid = true;
24
        String cookieValue = this.getCookie(request,"AccessToken");
25
        if(cookieValue == null || cookieValue.isEmpty()){
26
            log.info("no cookie available ");
27
            valid = false;
28
        }else {
29
            String headerValue = this.getHeadersInfo(request, "x-xsrf-token");
30
            if(headerValue == null || headerValue.isEmpty()){
31
                log.info("no header available ");
32
                valid = false;
33
            }else{
34
                if(!cookieValue.equals(headerValue)){
35
                    log.info("no proper header or cookie ");
36
                    valid = false;
37
                }else if(!hasValidOrigin(this.getHeadersInfo(request, "origin"))){
38
                    log.info("no proper origin ");
39
                    valid = false;
40
                }
41
            }
42
        }
43
        return valid;
44
    }
45
    public String getToken(HttpServletRequest request){
46
        return this.getHeadersInfo(request, "x-xsrf-token");
47
    }
48
    private String getCookie(HttpServletRequest request, String cookieName){
49
        if(request.getCookies() == null){
50
            return null;
51
        }
52
        for(Cookie c: request.getCookies()){
53
//            log.debug("cookie "+ c.getName()+ " "+ c.getValue());
54
            if(c.getName().equals(cookieName)){
55
                return c.getValue();
56
            }
57

  
58
        }
59
        return null;
60
    }
61
    private String getHeadersInfo(HttpServletRequest request, String name) {
62

  
63
        Enumeration headerNames = request.getHeaderNames();
64
        while (headerNames.hasMoreElements()) {
65
            String key = (String) headerNames.nextElement();
66
            String value = request.getHeader(key);
67
//            log.debug(" key: "+ key+" value: "+ value);
68
            if(name.equals(key)){
69
                return value;
70
            }
71
        }
72
        return null;
73
    }
74
    public boolean hasValidOrigin(String origin) {
75
        if (origin != null && origin.indexOf(originServer)!=-1) {
76
            return true;
77
        }
78
        log.debug("Not valid origin. Origin server is \"" + origin + "\", but expected value is \"" + originServer + "\". If the expec cted value is not right, check properties file. ");
79
        return false;
80
    }
81
    public  UserInfo getUserInfo(String accessToken){
82
        String url=userInfoUrl+accessToken;
83
        URL obj = null;
84
        String responseStr=null;
85
//        log.debug("User info url is "+url);
86

  
87
        try {
88
            obj = new URL(url);
89
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
90
            if (con.getResponseCode() != 200) {
91
                log.debug("User info response code is: " + con.getResponseCode());
92
                return null;
93
            }
94
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
95
            StringBuffer response = new StringBuffer();
96
            String inputLine;
97
            while ((inputLine = in.readLine()) != null) {
98
                response.append(inputLine).append("\n");
99
            }
100
            in.close();
101
            responseStr = response.toString();
102
        }catch(Exception e){
103
            log.error("An error occured while trying to fetch user info ",e);
104
            return null;
105
        }
106
        return json2UserInfo(responseStr);
107
    }
108
    private  UserInfo json2UserInfo(String json) {
109

  
110
//        log.debug("Try to create userInfo class from json: "+json);
111
        if (json == null){
112
            return null;
113
        }
114

  
115
        BufferedReader br = new BufferedReader(new StringReader(json));
116
        //convert the json string back to object
117
        Gson gson = new Gson();
118
        UserInfo userInfo = null;
119
        try {
120
            userInfo = gson.fromJson(br, UserInfo.class);
121
        }catch(Exception e){
122
            log.debug("Error in parsing json response. Given json is : "+json, e);
123
            return null;
124
        }
125

  
126
//        log.debug("Original response.........: "+userInfo.toString());
127
        try {
128
            if(userInfo != null && userInfo.getEdu_person_entitlements() != null ) {
129

  
130
                for (int i = 0; i < userInfo.getEdu_person_entitlements().size(); i++) {
131
                    String role = userInfo.getEdu_person_entitlements().get(i);
132
//                    log.debug("AAI role: "+role);
133
                    role = role.split(":")[role.split(":").length-1];
134
                    role = role.replace("+"," ");
135
//                    log.debug("Adding parsed role : "+role);
136
                    userInfo.getEdu_person_entitlements().set(i,role);
137
                }
138
            }
139
        }catch(Exception e){
140
            log.debug("Error in parsing  Edu_person_entitlements : ",e);
141
            return null;
142
        }
143
//        log.debug("After handling roles : "+userInfo.toString());
144

  
145

  
146
        return userInfo;
147
    }
148
    public boolean isAuthorized(String token) {
149
        UserInfo userInfo = getUserInfo(token);
150
        if (userInfo != null ) {
151
            return true;
152
        } else {
153
            log.debug(" User has no Valid UserInfo");
154
            return false;
155
        }
156

  
157
    }
158

  
159
    public String getUserInfoUrl() {
160
        return userInfoUrl;
161
    }
162

  
163
    public String getOriginServer() {
164
        return originServer;
165
    }
166

  
167
    public void setUserInfoUrl(String userInfoUrl) {
168
        this.userInfoUrl = userInfoUrl;
169
    }
170

  
171
    public void setOriginServer(String originServer) {
172
        this.originServer = originServer;
173
    }
174
    //    private boolean hasRole(List<String> givenRoles, List<String> authorizedRoles) {
175
//        log.debug("It's  registered with role " + givenRoles);
176
//        for (String gRole : givenRoles) {
177
//            if (authorizedRoles.indexOf(gRole) != -1) {
178
//                return true;
179
//            }
180
//        }
181
//        log.debug("Not Authorized. Authorized roles are" + authorizedRoles);
182
//        return false;
183
//
184
//    }
185
//    private boolean isCommunityManager(String community, String email) {
186
//
187
//        CommunityInfo communityInfo = getCommunityInfo(community);
188
//        if(communityInfo != null && communityInfo.getManagers() != null ) {
189
//
190
//            for (int i = 0; i < communityInfo.getManagers().size(); i++) {
191
//                String manager = communityInfo.getManagers().get(i);
192
//                log.debug("Community manager: "+manager);
193
//
194
//            }
195
//        }
196
//        return false;
197
//
198
//    }
199
//    private CommunityInfo getCommunityInfo(String community) {
200
//        String url = userInfoUrl + community;
201
//        URL obj = null;
202
//        String responseStr = null;
203
//        log.debug("Community info url is " + url);
204
//
205
//        try {
206
//            obj = new URL(url);
207
//            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
208
//            log.debug("User info response code is: " + con.getResponseCode());
209
//            if (con.getResponseCode() != 200) {
210
//                return null;
211
//            }
212
//            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
213
//            StringBuffer response = new StringBuffer();
214
//            String inputLine;
215
//            while ((inputLine = in.readLine()) != null) {
216
//                response.append(inputLine).append("\n");
217
//            }
218
//            in.close();
219
//            responseStr = response.toString();
220
//        } catch (Exception e) {
221
//            log.error("An error occured while trying to fetch user info ", e);
222
//            return null;
223
//        }
224
//        return json2CommunityInfo(community);
225
//    }
226
//    private  CommunityInfo json2CommunityInfo(String json){
227
//
228
//        log.debug("Try to create CommunityInfo class from json: "+json);
229
//        if (json == null){
230
//            return null;
231
//        }
232
//
233
//        BufferedReader br = new BufferedReader(new StringReader(json));
234
//        //convert the json string back to object
235
//        Gson gson = new Gson();
236
//        CommunityInfo communityInfo = null;
237
//        try {
238
//            communityInfo = gson.fromJson(br, CommunityInfo.class);
239
//        }catch(Exception e){
240
//            log.debug("Error in parsing json response. Given json is : "+json, e);
241
//            return null;
242
//        }
243
//
244
//        log.debug("Original response.........: "+communityInfo.toString());
245
//
246
//
247
//
248
//        return communityInfo;
249
//    }
250
}
modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceApplication.java
1 1
package eu.dnetlib.uoamonitorservice;
2 2

  
3
import eu.dnetlib.uoaauthorizationlibrary.configuration.AuthorizationConfiguration;
3 4
import eu.dnetlib.uoamonitorservice.configuration.properties.MongoConfig;
4
import eu.dnetlib.uoamonitorservice.configuration.properties.SecurityConfig;
5 5
import org.springframework.boot.SpringApplication;
6 6
import org.springframework.boot.autoconfigure.SpringBootApplication;
7 7
import org.springframework.boot.context.properties.EnableConfigurationProperties;
8
import org.springframework.context.annotation.Import;
8 9
import org.springframework.context.annotation.PropertySource;
9 10
import org.springframework.context.annotation.PropertySources;
10 11
//uoahelptexts
11
@SpringBootApplication(scanBasePackages = {"eu.dnetlib.uoamonitorservice", "eu.dnetlib.uoaadmintoolslibrary"})
12
@SpringBootApplication(scanBasePackages = {"eu.dnetlib.uoamonitorservice", "eu.dnetlib.uoaadmintoolslibrary"
13
//        , "eu.dnetlib.uoaauthorizationlibrary"
14
})
12 15
@PropertySources({
16
        @PropertySource("classpath:authorization.properties"),
13 17
        @PropertySource("classpath:monitorservice.properties"),
14
//        @PropertySource(value = "file:/usr/share/tomcat7/lib/dnet-override.properties", ignoreResourceNotFound = true),
15
//        @PropertySource(value = "file:/var/lib/tomcat_dnet/8380/lib/dnet-override.properties", ignoreResourceNotFound = true),
16
//        @PropertySource(value = "file:/var/lib/tomcat8/lib/dnet-override.properties", ignoreResourceNotFound = true)
17
        @PropertySource("classpath:dnet-override.properties")
18
        @PropertySource(value = "classpath:dnet-override.properties", ignoreResourceNotFound = true)
18 19
})
19 20

  
20
@EnableConfigurationProperties({SecurityConfig.class, MongoConfig.class})
21
//SecurityConfig.class,
22
@EnableConfigurationProperties({ MongoConfig.class})
21 23

  
24
@Import(AuthorizationConfiguration.class)
22 25
public class UoaMonitorServiceApplication {
23 26
    public static void main(String[] args) {
24 27
        SpringApplication.run(UoaMonitorServiceApplication.class, args);
modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/UoaMonitorServiceConfiguration.java
1 1
package eu.dnetlib.uoamonitorservice;
2 2

  
3
import eu.dnetlib.uoamonitorservice.configuration.properties.SecurityConfig;
4
import eu.dnetlib.uoamonitorservice.handlers.AuthorizationHandler;
5 3
import org.apache.log4j.Logger;
6
import org.springframework.beans.factory.annotation.Autowired;
7 4
import org.springframework.context.annotation.Bean;
8 5
import org.springframework.context.annotation.Configuration;
9 6
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
10
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
11 7
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
12 8

  
13 9
@Configuration
14 10
public class UoaMonitorServiceConfiguration extends WebMvcConfigurerAdapter {
15 11
    private final Logger log = Logger.getLogger(this.getClass());
16 12

  
17
    @Autowired
18
    private SecurityConfig securityConfig;
19

  
20

  
21 13
    @Bean
22 14
    public static PropertySourcesPlaceholderConfigurer  propertySourcesPlaceholderConfigurer() {
23 15
        return new PropertySourcesPlaceholderConfigurer();
24 16
    }
25

  
26
    @Override
27
    public void addInterceptors(InterceptorRegistry registry) {
28
        registry.addInterceptor(new AuthorizationHandler(securityConfig.getUserInfoUrl(), securityConfig.getOriginServer(), securityConfig.getPostsAllowed()))
29
                .addPathPatterns("/**");
30

  
31
    }
32

  
33 17
}
modules/uoa-monitor-service/trunk/src/main/java/eu/dnetlib/uoamonitorservice/configuration/properties/SecurityConfig.java
1
package eu.dnetlib.uoamonitorservice.configuration.properties;
2

  
3
import org.springframework.boot.context.properties.ConfigurationProperties;
4

  
5
import java.util.ArrayList;
6
import java.util.List;
7

  
8
@ConfigurationProperties("monitorservice.security")
9
public class SecurityConfig {
10

  
11
    private String userInfoUrl;
12
    private String originServer;
13
    private List<String> postsAllowed = new ArrayList<>();
14

  
15
    public void setUserInfoUrl(String userInfoUrl) {
16
        this.userInfoUrl = userInfoUrl;
17
    }
18

  
19
    public void setOriginServer(String originServer) {
20
        this.originServer = originServer;
21
    }
22

  
23

  
24
    public void setPostsAllowed(List<String> posts) {
25
        this.postsAllowed = posts;
26
    }
27

  
28
    public String getUserInfoUrl() {
29
        return userInfoUrl;
30
    }
31

  
32
    public String getOriginServer() {
33
        return originServer;
34
    }
35

  
36
    public List<String> getPostsAllowed() {
37
        return postsAllowed;
38
    }
39

  
40
}
modules/uoa-monitor-service/trunk/src/main/resources/monitorservice.properties
1 1
#dev
2
monitorservice.userInfoUrl = http://scoobydoo.di.uoa.gr:8080/dnet-openaire-users-1.0.0-SNAPSHOT/api/users/getUserInfo?accessToken=
3
monitorservice.originServer = .di.uoa.gr
4 2
monitorservice.host = smtp.gmail.com
5 3
monitorservice.port = 587
6 4
monitorservice.auth = true
7 5
monitorservice.from = openaire.test@gmail.com
8 6
monitorservice.username = openaire.test@gmail.com
9 7
monitorservice.password = ...
8
monitorservice.mongodb.host=localhost
9
monitorservice.mongodb.port=27017
10
monitorservice.mongodb.database=openaire_monitor3
10 11

  
11 12
#beta
12 13
#monitorservice.userInfoUrl =  https://beta.services.openaire.eu/uoa-user-management/api/users/getUserInfo?accessToken=
modules/uoa-monitor-service/trunk/pom.xml
14 14
    <parent>
15 15
        <groupId>org.springframework.boot</groupId>
16 16
        <artifactId>spring-boot-starter-parent</artifactId>
17
        <version>1.5.18.RELEASE</version>
17
        <version>1.5.8.RELEASE</version>
18 18
        <relativePath/> <!-- lookup parent from repository -->
19 19
    </parent>
20 20

  
......
73 73
            <version>1.0.0-SNAPSHOT</version>
74 74
        </dependency>
75 75
        <dependency>
76
            <groupId>eu.dnetlib</groupId>
77
            <artifactId>uoa-authorization-library</artifactId>
78
            <version>1.0.0-SNAPSHOT</version>
79
        </dependency>
80
        <dependency>
76 81
            <groupId>org.springframework.boot</groupId>
77 82
            <artifactId>spring-boot-starter-test</artifactId>
78 83
            <scope>test</scope>
79 84
        </dependency>
85
        <dependency>
86
            <groupId>org.springframework.boot</groupId>
87
            <artifactId>spring-boot-starter-security</artifactId>
88
        </dependency>
80 89
    </dependencies>
81 90

  
82 91
    <build>

Also available in: Unified diff