Project

General

Profile

« Previous | Next » 

Revision 49977

Added by Sofia Baltzi over 6 years ago

Moved classes to dnet-openaire-users

View differences:

modules/uoa-user-management/branches/redis/src/main/java/eu/dnetlib/openaire/user/security/JWTGenerator.java
1
package eu.dnetlib.openaire.user.security;
2

  
3
import com.google.gson.JsonObject;
4
import eu.dnetlib.openaire.user.MigrationUser;
5
import io.jsonwebtoken.Claims;
6
import io.jsonwebtoken.Jwts;
7
import io.jsonwebtoken.SignatureAlgorithm;
8
import org.apache.log4j.Logger;
9
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
10
import org.mitre.openid.connect.model.UserInfo;
11

  
12
import java.io.UnsupportedEncodingException;
13
import java.net.URLEncoder;
14
import java.text.ParseException;
15
import java.util.Date;
16

  
17
public class JWTGenerator {
18

  
19
    private static final Logger logger = Logger.getLogger(JWTGenerator.class);
20

  
21
    public static String generateToken(MigrationUser u, String secret) {
22
        Claims claims = Jwts.claims().setSubject(u.getUsername());
23
        claims.put("fullname", u.getFullname() + "");
24
        claims.put("userId", u.getId() + "");
25
        claims.put("email", u.getEmail() + "");
26
        claims.put("role", u.getRoleId());
27

  
28
        //expiration
29
        long nowMillis = System.currentTimeMillis();
30
        Date now = new Date(nowMillis);
31
        long ttlMillis = 1800000;
32
        long expMillis = nowMillis + ttlMillis;
33
        Date exp = new Date(expMillis);
34

  
35
        return Jwts.builder()
36
                .setClaims(claims)
37
                .setExpiration(exp)
38
                .signWith(SignatureAlgorithm.HS512, secret)
39
                .compact();
40
    }
41

  
42
    public static String generateToken(OIDCAuthenticationToken authOIDC, String secret) {
43

  
44
        try {
45

  
46
            JsonObject userInfo = authOIDC.getUserInfo().getSource();
47
            Claims claims = Jwts.claims().setSubject(authOIDC.getUserInfo().getSub());
48
            claims.put("fullname", URLEncoder.encode(authOIDC.getUserInfo().getName(), "UTF-8") + "");
49

  
50
            if (authOIDC.getUserInfo().getGivenName() == null){
51
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
52
                claims.put("firstname", URLEncoder.encode(" ", "UTF-8") + "");
53
            } else {
54
                claims.put("firstname", URLEncoder.encode(authOIDC.getUserInfo().getGivenName(), "UTF-8") + "");
55

  
56
            }
57
            if (authOIDC.getUserInfo().getFamilyName() == null){
58
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have first name");
59
                claims.put("lastname", URLEncoder.encode(" ", "UTF-8") + "");
60
            } else {
61
                claims.put("lastname", URLEncoder.encode(authOIDC.getUserInfo().getFamilyName(), "UTF-8") + "");
62

  
63
            }
64
            claims.put("email", authOIDC.getUserInfo().getEmail() + "");
65
//            claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
66
//
67

  
68
//            if (userInfo.getAsJsonArray("eduPersonScopedAffiliation").toString() != null) {
69
//                claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + "");
70
//            }
71

  
72
            if (userInfo.getAsJsonArray("edu_person_entitlements") == null){
73
                logger.info("User: " + authOIDC.getUserInfo().getName() + "doesn't have role");
74
                claims.put("role", URLEncoder.encode(" ", "UTF-8") + "");
75
            } else {
76
                claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
77
            }
78

  
79
            //TODO remove, We don't need it but if we are going to use it, we need to check if the user has affiliation
80
            //claims.put("edu_person_scoped_affiliations", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString(), "UTF-8") + "");
81

  
82
            //TODO remove
83
            //TODO THIS IS TEST
84
//            claims.put("fullname", URLEncoder.encode("Σοφία Μπαλτζή", "UTF-8") + "");
85
//            claims.put("firstname", URLEncoder.encode("Σοφία", "UTF-8") + "");
86
//            claims.put("lastname", URLEncoder.encode("Μπαλτζή", "UTF-8") + "");
87
//            claims.put("email", "sofie.mpl@gmail.com" + "");
88
//            claims.put("edu_person_scoped_affiliations", "faculty");
89

  
90
            Date exp = new Date(authOIDC.getIdToken().getJWTClaimsSet().getExpirationTime().getTime());
91

  
92
            //TODO DELETE LOGS
93
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
94
//            logger.info("fullName: " + authOIDC.getUserInfo().getName());
95
//            logger.info("firstName: " + authOIDC.getUserInfo().getGivenName());
96
//            logger.info("lastName: " + authOIDC.getUserInfo().getFamilyName());
97
//            logger.info("email: " + authOIDC.getUserInfo().getEmail());
98
//            //logger.info("Check everything");
99
//            logger.info("locale: " + authOIDC.getUserInfo().getSource());
100
//            logger.info("role: " + userInfo.getAsJsonArray("edu_person_entitlements").toString());
101
//            //logger.info("affiliation: " + userInfo.getAsJsonArray("edu_person_scoped_affiliations").toString());
102
//            logger.info("expirationTime: " + exp);
103
//            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
104

  
105
            return Jwts.builder()
106
                    .setClaims(claims)
107
                    .setExpiration(exp)
108
                    .signWith(SignatureAlgorithm.HS512, secret)
109
                    .compact();
110

  
111
        } catch (ParseException e) {
112
            e.printStackTrace();
113
            logger.error("JWT Parse Exception from getting Expiration Time ", e);
114
            return "error";
115
        } catch (UnsupportedEncodingException e) {
116
            e.printStackTrace();
117
            logger.error("UnsupportedEncodingException UTF-8 ", e);
118
            return "error";
119
        }
120
    }
121

  
122
    //TODO DELETE IF IT IS NOT NECESSARY
123
    public static String generateAccessToken(OIDCAuthenticationToken authOIDC, String secret) {
124
        Claims claims = Jwts.claims().setId(authOIDC.getAccessTokenValue());
125

  
126
        //TODO DELETE LOGS
127
        logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
128
        logger.info("access token: " + authOIDC.getAccessTokenValue());
129
        logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
130

  
131
        return Jwts.builder()
132
                .setClaims(claims)
133
                .signWith(SignatureAlgorithm.HS512, secret)
134
                .compact();
135
    }
136

  
137

  
138
    public static String generateToken(UserInfo user, String secret) {
139
        try {
140

  
141
            JsonObject userInfo = user.getSource();
142

  
143
        Claims claims = Jwts.claims().setSubject(user.getSub());
144
        claims.put("email", user.getEmail() + "");
145
            claims.put("role", URLEncoder.encode(userInfo.getAsJsonArray("edu_person_entitlements").toString(), "UTF-8") + "");
146

  
147
        return Jwts.builder()
148
                .setClaims(claims)
149
                .signWith(SignatureAlgorithm.HS512, secret)
150
                .compact();
151
        } catch (UnsupportedEncodingException e) {
152
            e.printStackTrace();
153
            logger.error("UnsupportedEncodingException UTF-8 ", e);
154
            return "error";
155
        }
156
    }
157

  
158
}
159

  
160

  
161

  
162
// How to add it manually
163
//        long nowMillis = System.currentTimeMillis();
164
//        //This is my token
165
//        try {
166
//            String jwt = Jwts.builder()
167
//                    .setSubject("Argiro")
168
//                    .setExpiration(new Date(nowMillis+1800000))
169
//                    .claim("fullname", "Argiro Kokogianaki")
170
//                    .claim("id", "8")
171
//                    .claim("email", "argiro@gmail.com")
172
//                    .claim("role","2")
173
//                    .signWith(
174
//                            SignatureAlgorithm.HS512,
175
//                            "my-very-secret".getBytes("UTF-8")
176
//                    )
177
//                    .compact();
modules/uoa-user-management/branches/redis/src/main/java/eu/dnetlib/openaire/user/security/FrontEndLinkURIAuthenticationSuccessHandler.java
1
package eu.dnetlib.openaire.user.security;
2

  
3
import com.sun.org.apache.xpath.internal.SourceTree;
4
import org.apache.log4j.Logger;
5
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
6
import org.springframework.security.core.Authentication;
7
import org.springframework.security.core.context.SecurityContextHolder;
8
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
9

  
10
import javax.servlet.ServletException;
11
import javax.servlet.http.Cookie;
12
import javax.servlet.http.HttpServletRequest;
13
import javax.servlet.http.HttpServletResponse;
14
import java.io.IOException;
15
import java.net.URLEncoder;
16
import java.text.ParseException;
17
import java.util.Date;
18

  
19
/**
20
 * Created by stefanos on 9/5/2017.
21
 */
22
public class FrontEndLinkURIAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
23

  
24
    private static final Logger logger = Logger.getLogger(FrontEndLinkURIAuthenticationSuccessHandler.class);
25

  
26
    private String frontEndURI;
27
    private String frontPath;
28
    private String frontDomain;
29

  
30
    @Override
31
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IllegalArgumentException, IOException   {
32

  
33
        OIDCAuthenticationToken authOIDC = (OIDCAuthenticationToken) authentication;
34

  
35
        try {
36

  
37
            Cookie jwt = new Cookie("XCsrfToken", JWTGenerator.generateToken(authOIDC, "my-very-secret"));
38
            Cookie accessToken = new Cookie("AccessToken", authOIDC.getAccessTokenValue());
39

  
40
            // Expire the cookies in four hours (4 * 3600)
41
            jwt.setMaxAge(14400);
42
            accessToken.setMaxAge(14400);
43

  
44
            //TODO DELETE LOG
45
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
46
            logger.info("access token: " + authOIDC.getAccessTokenValue());
47
            logger.info("\n////////////////////////////////////////////////////////////////////////////////////////////////\n");
48

  
49
            jwt.setPath(frontPath);
50
            jwt.setDomain(frontDomain);
51
            accessToken.setPath(frontPath);
52
            accessToken.setDomain(frontDomain);
53

  
54
            response.addCookie(jwt);
55
            response.addCookie(accessToken);
56
            response.sendRedirect(frontEndURI);
57

  
58
        } catch (IOException e) {
59
            logger.error("IOException in redirection ", e);
60
            throw new IOException(e);
61
        }catch (IllegalArgumentException e) {
62
            logger.error("IllegalArgumentException in redirection ", e);
63
            throw new IllegalArgumentException(e);
64
        }
65

  
66
    }
67

  
68
    public String getFrontEndURI() {
69
        return frontEndURI;
70
    }
71

  
72
    public void setFrontEndURI(String frontEndURI) {
73
        this.frontEndURI = frontEndURI;
74
    }
75

  
76
    public String getFrontPath() {
77
        return frontPath;
78
    }
79

  
80
    public void setFrontPath(String frontPath) {
81
        this.frontPath = frontPath;
82
    }
83

  
84
    public String getFrontDomain() {
85
        return frontDomain;
86
    }
87

  
88
    public void setFrontDomain(String frontDomain) {
89
        this.frontDomain = frontDomain;
90
    }
91
}
92

  
93

  
modules/uoa-user-management/branches/redis/src/main/java/eu/dnetlib/openaire/user/api/services/Test3Service.java
1
package eu.dnetlib.openaire.user.api.services;
2

  
3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
import com.google.gson.Gson;
6
import com.google.gson.JsonObject;
7
import com.google.gson.JsonParser;
8
import com.unboundid.ldap.sdk.LDAPException;
9
import eu.dnetlib.openaire.user.LDAPUser;
10
import eu.dnetlib.openaire.user.MigrationUser;
11
import eu.dnetlib.openaire.user.Role;
12
import eu.dnetlib.openaire.user.dao.RoleDAO;
13
import eu.dnetlib.openaire.user.dao.SQLMigrationUserDAO;
14
import eu.dnetlib.openaire.user.ldap.MUserActionsLDAP;
15
import eu.dnetlib.openaire.user.security.JWTGenerator;
16
import eu.dnetlib.openaire.user.store.DataSourceConnector;
17
import org.apache.log4j.Logger;
18
import org.mitre.openid.connect.model.UserInfo;
19
import org.springframework.beans.factory.annotation.Autowired;
20
import org.springframework.http.*;
21
import org.springframework.http.HttpMethod;
22
import org.springframework.stereotype.Component;
23
import org.springframework.web.client.RestTemplate;
24

  
25
import javax.ws.rs.*;
26
import javax.ws.rs.core.MediaType;
27
import javax.ws.rs.core.Response;
28
import java.io.OutputStream;
29
import java.sql.SQLException;
30

  
31
/**
32
 * Created by sofia on 24/11/2016.
33
 */
34
@Component(value = "test3service")
35
@Path("/users")
36
public class Test3Service {
37

  
38
    private static final Logger logger = Logger.getLogger(Test3Service.class);
39

  
40
    @Autowired
41
    private SQLMigrationUserDAO sqlMigrationUserDAO;
42

  
43
    @Autowired
44
    private MUserActionsLDAP mUserActionsLDAP;
45

  
46
    @Autowired
47
    private DataSourceConnector dataSourceConnector;
48

  
49
    @GET
50
    @Path("/{userId}")
51
    @Produces(MediaType.APPLICATION_JSON)
52
    public Response getUserById(@PathParam("userId") int userId) {
53
        try {
54
            MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId);
55

  
56
            // Invalide user ID
57
            if (mUser == null) {
58
                String errorMessageJson = compose404Message("Cannot find user with id " + userId + ".");
59

  
60
                return Response
61
                        .status(Response.Status.NOT_FOUND)
62
                        .entity(errorMessageJson)
63
                        .type(MediaType.APPLICATION_JSON)
64
                        .build();
65
            }
66

  
67
            return Response.status(200).entity(composeDataResponse(mUser)).build();
68
        }
69
        catch (SQLException e) {
70
            return Response
71
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
72
                    .entity(compose500Message("Fail to fetch users.", e))
73
                    .type(MediaType.APPLICATION_JSON)
74
                    .build();
75
        }
76
    }
77

  
78
     /* How to check @browser ../authenticate/?username=MY_USERNAME&password=MY_PASSWORD
79
     * http://localhost:8080/uoa-user-management-1.0.0-SNAPSHOT/api/users/authenticate?username=sba&password=12345678
80
    @GET
81
    @Path("/authenticate")
82
    @Produces(MediaType.APPLICATION_JSON)
83
    public Response authenticateUserGET(@QueryParam("username") String username, @QueryParam("password") String password)
84
    {
85
        return commonAuthenticateFunction(username, password);
86

  
87
    }*/
88

  
89
    @POST
90
    @Path("/authenticates")
91
    @Produces(MediaType.APPLICATION_JSON)
92
    @Consumes(MediaType.APPLICATION_JSON)
93
    public Response authenticateUserPOST(String input) {
94
        JsonObject jsonObject = new JsonParser().parse(input).getAsJsonObject();
95

  
96
        String username = jsonObject.get("username").getAsString();
97
        String password = jsonObject.get("password").getAsString();
98

  
99
        return commonAuthenticateFunction(username, password);
100
    }
101

  
102
    private Response commonAuthenticateFunction(String username, String password)
103
    {
104
        try {
105
            boolean usernameExists = mUserActionsLDAP.usernameExists(username);
106

  
107
            // if user was not found
108
            if (!usernameExists) {
109
                String errorMessageJson = compose401Message("Wrong credentials.");
110

  
111
                return Response
112
                        .status(Response.Status.UNAUTHORIZED)
113
                        .entity(errorMessageJson)
114
                        .type(MediaType.APPLICATION_JSON)
115
                        .build();
116
            }
117

  
118
            boolean authenticated = mUserActionsLDAP.authenticate(username, password);
119

  
120
            // if user was not authenticated
121
            if (!authenticated) {
122
                return Response
123
                        .status(Response.Status.UNAUTHORIZED)
124
                        .entity(compose401Message("User " + username + " could not be authenticated."))
125
                        .type(MediaType.APPLICATION_JSON)
126
                        .build();
127
            }
128

  
129
            MigrationUser mUser = sqlMigrationUserDAO.fetchByUsername(username);
130

  
131
            // if user was not found in my db
132
            LDAPUser ldapUser = null;
133
            if (mUser == null) {
134
                mUser = new MigrationUser(username);
135
                ldapUser = mUserActionsLDAP.getUser(username);
136
                mUser.setFullname(ldapUser.getDisplayName());
137
                mUser.setEmail(ldapUser.getEmail());
138
                mUser.setRoleId(2);
139

  
140

  
141
                sqlMigrationUserDAO.insert(mUser);
142
            }
143
            return Response.status(200).entity(composeDataResponse(mUser)).type(MediaType.APPLICATION_JSON).build();
144

  
145
        } catch (LDAPException exc) {
146
            logger.error("Fail to connect to LDAP. ", exc);
147
            return Response
148
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
149
                    .entity(compose500Message("LDAP error.", exc))
150
                    .type(MediaType.APPLICATION_JSON)
151
                    .build();
152

  
153
        } catch (SQLException exc) {
154
            logger.error("Fail to fetch users. ", exc);
155
            return Response
156
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
157
                    .entity(compose500Message("Fail to fetch users.", exc))
158
                    .type(MediaType.APPLICATION_JSON)
159
                    .build();
160
        }
161

  
162
    }
163

  
164
    @GET
165
    @Path("/changeRole")
166
    @Produces(MediaType.APPLICATION_JSON)
167
    public Response changeRole(@QueryParam("roleId") int roleId, @QueryParam("userId") int userId)
168
    {
169
        RoleDAO roleDAO = new RoleDAO();
170
        try
171
        {
172
            Role role = roleDAO.fetchById(roleId);
173
            if (role == null)
174
            {
175
                //fetch all roleids TODO
176
                String errorMessageJson = compose404Message("Cannot find role with id" + roleId + ".");
177

  
178
                return Response
179
                        .status(Response.Status.NOT_FOUND)
180
                        .entity(errorMessageJson)
181
                        .type(MediaType.APPLICATION_JSON)
182
                        .build();
183
            }
184

  
185
            MigrationUser mUser = sqlMigrationUserDAO.fetchById(userId);
186

  
187
            if (mUser == null)
188
            {
189
                String errorMessageJson = compose404Message("Cannot find user with id " + userId + ".");
190

  
191
                return Response
192
                        .status(Response.Status.NOT_FOUND)
193
                        .entity(errorMessageJson)
194
                        .type(MediaType.APPLICATION_JSON)
195
                        .build();
196
            }
197

  
198
            mUser.setRoleId(roleId);
199
            sqlMigrationUserDAO.update(mUser);
200

  
201
            return Response.status(200).entity(composeDataResponse(mUser)).build();
202
        }
203
        catch (SQLException exc)
204
        {
205
            return Response
206
                    .status(Response.Status.INTERNAL_SERVER_ERROR)
207
                    .entity(compose500Message("Fail to fetch users.", exc))
208
                    .type(MediaType.APPLICATION_JSON)
209
                    .build();
210
        }
211
    }
212

  
213
    @GET
214
    @Path("/getUserInfo")
215
    @Produces(MediaType.APPLICATION_JSON)
216
    public Response getUserInfo(@QueryParam("accessToken") String accessToken) throws JsonProcessingException {
217

  
218
        //return Response.status(404).entity(compose404Message("This is a test message.")).type(MediaType.APPLICATION_JSON).build();
219

  
220
        // call aai with accessToken
221
        RestTemplate restTemplate = new RestTemplate();
222
        HttpHeaders headers = new HttpHeaders();
223
        headers.add("Authorization","Bearer " + accessToken);
224
        HttpEntity request = new HttpEntity(null, headers);
225
        String fooResourceUrl = "https://aai.openminted.eu/oidc/userinfo";
226
        logger.info(restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class));
227
        ResponseEntity response1 = restTemplate.exchange(fooResourceUrl, HttpMethod.GET, request, Object.class);
228
        logger.info(response1.getBody().toString());
229
        ObjectMapper mapper = new ObjectMapper();
230

  
231
        return Response.status(response1.getStatusCode().value()).entity(mapper.writeValueAsString(response1.getBody())).type(MediaType.APPLICATION_JSON).build();
232

  
233
    }
234

  
235
    /* JSON Utility Methods */
236

  
237
    private String compose401Message(String message) {
238
        return  "{ \"status\" : \"error\", \"code\" : \"401\", \"message\" : \"  " + message +" \" }";
239
    }
240

  
241
    private String compose404Message(String message) {
242
        return  "{ \"status\" : \"error\", \"code\" : \"404\", \"message\" : \"  " + message +" \" }";
243
    }
244

  
245
    private String compose500Message(String message, Exception exception) {
246
        return  "{ \"status\" : \"fail\", \"code\" : \"500\", \"message\" : \"  " + message + "\", " +
247
                "\"description\" : \""+  exception.getMessage() +"\" }";
248
    }
249

  
250
    private String composeDataResponse(UserInfo user) {
251
        return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }";
252
    }
253

  
254
    private String composeDataResponse(MigrationUser user) {
255
        //return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
256
        return "{ \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : \"" + JWTGenerator.generateToken(user, "my-very-secret") + "\" }";
257
    }
258

  
259
    private String composeDataResponse(LDAPUser user) {
260
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(user) + " }";
261
    }
262

  
263
//        private String composeDataResponse(String username) {
264
//            return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(username) + " }";
265
//        }
266

  
267
    private String composeDataResponse(String fullname) {
268
        return " { \"status\" : \"success\", \"code\": \"200\", " + "\"data\" : " + new Gson().toJson(fullname) + " }";
269
    }
270
}

Also available in: Unified diff