SingleSignOnInterceptor.java 2.4 KB
Newer Older
M
MaxKey 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright [2022] [MaxKey of copyright http://www.maxkey.top]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 

package org.maxkey.web.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

M
MaxKey 已提交
22
import org.maxkey.authn.jwt.AuthTokenService;
M
MaxKey 已提交
23
import org.maxkey.authn.session.SessionManager;
M
MaxKey 已提交
24
import org.maxkey.authn.web.AuthorizationUtils;
M
MaxKey 已提交
25
import org.maxkey.configuration.ApplicationConfig;
M
MaxKey 已提交
26 27 28 29 30 31 32 33 34 35 36 37
import org.maxkey.crypto.Base64Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

@Component
public class SingleSignOnInterceptor  implements AsyncHandlerInterceptor {
    private static final Logger _logger = LoggerFactory.getLogger(SingleSignOnInterceptor.class);
    
M
MaxKey 已提交
38 39
    @Autowired
    ApplicationConfig applicationConfig;
M
MaxKey 已提交
40 41
    
    @Autowired
M
MaxKey 已提交
42
	SessionManager sessionManager;
M
MaxKey 已提交
43 44
    
    @Autowired
M
MaxKey 已提交
45
	AuthTokenService authTokenService ;
M
MaxKey 已提交
46 47 48 49 50
    
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler)
            throws Exception {
M
MaxKey 已提交
51
    	_logger.trace("Single Sign On Interceptor");
M
MaxKey 已提交
52 53
       
    	AuthorizationUtils.authenticateWithCookie(
M
MaxKey 已提交
54
    				request,authTokenService,sessionManager);
M
MaxKey 已提交
55

M
MaxKey 已提交
56
        if(AuthorizationUtils.isNotAuthenticated()){
M
MaxKey 已提交
57 58 59 60 61
        	String loginUrl = applicationConfig.getFrontendUri() + "/#/passport/login?redirect_uri=%s";
        	String redirect_uri = UrlUtils.buildFullRequestUrl(request);
        	String base64RequestUrl = Base64Utils.base64UrlEncode(redirect_uri.getBytes());
        	_logger.debug("No Authentication ... Redirect to /passport/login , redirect_uri {}",redirect_uri);
        	response.sendRedirect(String.format(loginUrl,base64RequestUrl));
M
MaxKey 已提交
62 63 64 65 66
        }
        return true;
    }

}