· 6 years ago · Mar 10, 2020, 07:22 AM
1package com.wso2.eca.client.api.filter;
2
3import com.google.gson.Gson;
4import com.nimbusds.jose.JOSEException;
5import com.nimbusds.jose.JWSVerifier;
6import com.nimbusds.jose.crypto.RSASSAVerifier;
7import com.nimbusds.jwt.SignedJWT;
8import com.wso2.eca.client.model.APIResponse;
9import com.wso2.eca.client.utils.Constant;
10import com.wso2.eca.client.utils.ExecutionUtils;
11import org.apache.commons.lang3.StringUtils;
12import org.slf4j.Logger;
13import org.slf4j.LoggerFactory;
14
15import javax.servlet.*;
16import javax.servlet.http.HttpServletRequest;
17import javax.servlet.http.HttpServletResponse;
18import java.io.IOException;
19import java.io.InputStream;
20import java.security.KeyStore;
21import java.security.KeyStoreException;
22import java.security.NoSuchAlgorithmException;
23import java.security.PublicKey;
24import java.security.cert.Certificate;
25import java.security.cert.CertificateException;
26import java.security.interfaces.RSAPublicKey;
27import java.text.ParseException;
28import java.util.Enumeration;
29
30public class AuthFilter implements Filter {
31
32 private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class);
33
34 private static final String API_URL_PREFIX = "/api/";
35 private static final int SESSION_VALID_PERIOD = 60 * 60;
36
37 @Override
38 public void init(FilterConfig filterConfig) throws ServletException {
39
40 }
41
42 @Override
43 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
44 throws IOException, ServletException {
45 HttpServletRequest request = (HttpServletRequest) servletRequest;
46 HttpServletResponse response = (HttpServletResponse) servletResponse;
47
48 // API calls and page requests are handled separately.
49 // API calls shouldn't receive redirect responses while pages should
50 String url = request.getRequestURL().toString();
51 if (url.contains(API_URL_PREFIX)) {
52 logger.info("Received API call to " + url);
53 filterAPIRequest(request, response, filterChain);
54 } else {
55 logger.info("Received page request for " + url);
56 filterPageRequest(request, response, filterChain);
57 }
58 }
59
60 @Override
61 public void destroy() {
62
63 }
64
65 private void filterAPIRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
66 throws IOException, ServletException {
67
68 // if session exists allow user access
69
70 if (request.getSession().getAttribute(Constant.Session.EMAIL) != null
71 && request.getSession().getAttribute(Constant.Session.ROLES) != null) {
72 if (logger.isDebugEnabled()) {
73 logger.debug("Allowing access to " + request.getRequestURL()
74 + " for user because the session present for user "
75 + request.getSession().getAttribute(Constant.Session.EMAIL));
76 }
77 filterChain.doFilter(request, response);
78 }
79 // else {
80 // APIResponse apiResponse = new APIResponse();
81 // apiResponse.setStatus(Constant.APIResponseStatus.NOT_LOGGED_IN);
82 // apiResponse.setMessage("Your session had expired. Please login.");
83 // apiResponse.setData(ExecutionUtils.getConfigValue(Constant.Config.CLIENT_SSO_URL));
84
85 // if (logger.isDebugEnabled()) {
86 // logger.debug("Declining access to " + request.getRequestURL() + " for user unknown user from "
87 // + request.getRemoteAddr());
88 // }
89 // response.getWriter().write(new Gson().toJson(apiResponse));
90 // }
91 }
92
93 private void filterPageRequest(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
94 throws IOException, ServletException {
95
96 String email = "malsha@wso2.com";
97 String roles = "admin";
98
99 // String email = null;
100 // String roles = null;
101
102 // String jwtString = request.getHeader("X-JWT-Assertion");
103 String ssoRedirectUrl = ExecutionUtils.getConfigValue(Constant.Config.CLIENT_SSO_URL);
104
105 // if (request.getSession().getAttribute(Constant.Session.EMAIL) != null
106 // && request.getSession().getAttribute(Constant.Session.ROLES) != null) {
107 // email = request.getSession().getAttribute(Constant.Session.EMAIL).toString();
108 // roles = request.getSession().getAttribute(Constant.Session.ROLES).toString();
109 // } else if (StringUtils.isNotBlank(jwtString)) {
110 // try {
111 // SignedJWT signedJWT = SignedJWT.parse(jwtString);
112
113 // PublicKey publicKey = getPublicKey();
114 // if (publicKey != null) {
115 // JWSVerifier verifier = new RSASSAVerifier((RSAPublicKey) publicKey);
116 // if (signedJWT.verify(verifier)) {
117 // if (logger.isDebugEnabled()) {
118 // logger.debug("JWT validation success for token {}", jwtString);
119 // }
120
121 // if (signedJWT.getJWTClaimsSet() != null) {
122 // email = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/emailaddress")
123 // .toString();
124 // roles = signedJWT.getJWTClaimsSet().getClaim("http://wso2.org/claims/role").toString();
125 // }
126
127 // } else {
128 // if (logger.isDebugEnabled()) {
129 // logger.debug("Declining access to " + request.getRequestURL() + " since JWT token "
130 // + jwtString + " is invalid");
131 // }
132 // }
133 // } else {
134 // if (logger.isDebugEnabled()) {
135 // logger.debug("Declining access to " + request.getRequestURL()
136 // + " since SSO Identity Provider public key does not exist");
137 // }
138 // }
139 // } catch (ParseException | CertificateException | NoSuchAlgorithmException | KeyStoreException
140 // | JOSEException e) {
141 // logger.error("Declining access to " + request.getRequestURL() + " since JWT token " + jwtString
142 // + " validation failed", e);
143 // }
144 // }
145
146 if (StringUtils.isNotBlank(email) && StringUtils.isNotBlank(roles)) {
147 request.getSession().setAttribute(Constant.Session.EMAIL, email);
148 request.getSession().setAttribute(Constant.Session.ROLES, roles);
149 request.getSession().setMaxInactiveInterval(SESSION_VALID_PERIOD);
150
151 if (logger.isDebugEnabled()) {
152 logger.debug("User data saved in session {email: {}, roles: {}}", email, roles);
153 }
154 filterChain.doFilter(request, response);
155 } else {
156 if (logger.isDebugEnabled()) {
157 logger.debug("Redirecting to {}", ssoRedirectUrl);
158 }
159 logger.info("Session error. Redirect should happen");
160 response.sendRedirect(ssoRedirectUrl);
161 }
162 }
163
164 private PublicKey getPublicKey()
165 throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {
166
167 // Loading the key store
168 KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
169 InputStream file = Thread.currentThread().getContextClassLoader()
170 .getResourceAsStream(Constant.KeyStore.KEYSTORE_FILE);
171 keystore.load(file, Constant.KeyStore.KEYSTORE_PASSWORD.toCharArray());
172
173 // Getting Identity Provider certificate (public key) from key store
174 Certificate cert = keystore.getCertificate(ExecutionUtils.getConfigValue(Constant.Config.KEYSTORE_ALIAS));
175
176 PublicKey publicKey = null;
177 if (cert != null) {
178 publicKey = cert.getPublicKey();
179 } else {
180 logger.error("SSO Identity Provider certificate does not exist in the internal key store");
181 }
182 return publicKey;
183 }
184}