net.ymate.module.sso.controller.SSOTokenController.java Source code

Java tutorial

Introduction

Here is the source code for net.ymate.module.sso.controller.SSOTokenController.java

Source

/*
 * Copyright 2007-2017 the original author or authors.
 *
 * 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 net.ymate.module.sso.controller;

import net.ymate.framework.commons.ParamUtils;
import net.ymate.framework.core.Optional;
import net.ymate.framework.webmvc.intercept.UserSessionStatusInterceptor;
import net.ymate.framework.webmvc.support.UserSessionBean;
import net.ymate.module.sso.ISSOToken;
import net.ymate.module.sso.ISSOTokenAttributeAdapter;
import net.ymate.module.sso.ISSOTokenStorageAdapter;
import net.ymate.module.sso.SSO;
import net.ymate.platform.core.beans.annotation.Before;
import net.ymate.platform.core.util.ExpressionUtils;
import net.ymate.platform.validation.validate.VRequired;
import net.ymate.platform.webmvc.annotation.Controller;
import net.ymate.platform.webmvc.annotation.RequestMapping;
import net.ymate.platform.webmvc.annotation.RequestParam;
import net.ymate.platform.webmvc.base.Type;
import net.ymate.platform.webmvc.context.WebContext;
import net.ymate.platform.webmvc.util.ErrorCode;
import net.ymate.platform.webmvc.util.WebResult;
import net.ymate.platform.webmvc.util.WebUtils;
import net.ymate.platform.webmvc.view.IView;
import net.ymate.platform.webmvc.view.View;
import net.ymate.platform.webmvc.view.impl.HttpStatusView;
import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author  (suninformation@163.com) on 17/5/4 ?1:29
 * @version 1.0
 */
@Controller
@RequestMapping("/sso")
public class SSOTokenController {

    /**
     * <p>
     * ?SSO?SSO??webmvc.redirect_login_url=sso/authorize?redirect_url=${redirect_url}??????????
     * </p>
     *
     * @param redirectUrl ??URL?
     * @return ???SSO(??)
     * @throws Exception ?
     */
    @RequestMapping("/authorize")
    @Before(UserSessionStatusInterceptor.class)
    public IView __toAuthorize(@RequestParam(Type.Const.REDIRECT_URL) String redirectUrl) throws Exception {
        if (StringUtils.isBlank(redirectUrl) || StringUtils.contains(redirectUrl, "/sso/authorize")) {
            return HttpStatusView.METHOD_NOT_ALLOWED;
        }
        if (UserSessionBean.current() != null) {
            return View.redirectView(redirectUrl);
        }
        //
        if (SSO.get().getModuleCfg().isClientMode()) {
            Map<String, String> _params = new HashMap<String, String>();
            _params.put(Type.Const.REDIRECT_URL, redirectUrl);
            // ???
            return View.redirectView(ParamUtils.appendQueryParamValue(
                    SSO.get().getModuleCfg().getServiceBaseUrl().concat("sso/authorize"), _params, true,
                    WebContext.getContext().getOwner().getModuleCfg().getDefaultCharsetEncoding()));
        }
        //
        ISSOToken _token = SSO.get().currentToken();
        if (_token != null) {
            Map<String, String> _params = new HashMap<String, String>();
            _params.put(SSO.get().getModuleCfg().getTokenParamName(),
                    SSO.get().getModuleCfg().getTokenAdapter().encryptToken(_token));
            // ????redirectUrl??token?
            return View.redirectView(ParamUtils.appendQueryParamValue(redirectUrl, _params, true,
                    WebContext.getContext().getOwner().getModuleCfg().getDefaultCharsetEncoding()));
        }
        // ????
        String _redirectUrl = WebUtils
                .buildRedirectURL(null, WebContext.getRequest(),
                        StringUtils.defaultIfBlank(WebContext.getContext().getOwner().getOwner().getConfig()
                                .getParam(Optional.REDIRECT_LOGIN_URL), "login?redirect_url=${redirect_url}"),
                        true);
        _redirectUrl = ExpressionUtils.bind(_redirectUrl)
                .set(Type.Const.REDIRECT_URL, WebUtils.encodeURL(redirectUrl)).getResult();
        return View.redirectView(_redirectUrl);
    }

    /**
     * @param tokenId    
     * @param uid        
     * @param remoteAddr IP?
     * @param sign       ???
     * @return ???
     * @throws Exception ?
     */
    @RequestMapping(value = "/authorize", method = Type.HttpMethod.POST)
    public IView __doAuthorize(@VRequired @RequestParam("token_id") String tokenId,
            @VRequired @RequestParam String uid, @VRequired @RequestParam("remote_addr") String remoteAddr,
            @VRequired @RequestParam String sign) throws Exception {

        if (SSO.get().getModuleCfg().isClientMode()) {
            return HttpStatusView.METHOD_NOT_ALLOWED;
        }
        //
        Map<String, String> _params = new HashMap<String, String>();
        _params.put("token_id", tokenId);
        _params.put("uid", uid);
        _params.put("remote_addr", remoteAddr);
        //
        String _sign = ParamUtils.createSignature(_params, false, SSO.get().getModuleCfg().getServiceAuthKey());
        if (StringUtils.equals(sign, _sign)) {
            ISSOTokenStorageAdapter _storageAdapter = SSO.get().getModuleCfg().getTokenStorageAdapter();
            // ???
            ISSOToken _token = _storageAdapter.load(uid, tokenId);
            if (_token != null) {
                boolean _ipCheck = (SSO.get().getModuleCfg().isIpCheckEnabled()
                        && !StringUtils.equals(remoteAddr, _token.getRemoteAddr()));
                if (_token.timeout() || !_token.verified() || _ipCheck) {
                    _storageAdapter.remove(_token.getUid(), _token.getId());
                    return WebResult.create(ErrorCode.USER_SESSION_INVALID_OR_TIMEOUT).toJSON();
                } else {
                    WebResult _result = WebResult.succeed();
                    // ?
                    ISSOTokenAttributeAdapter _attributeAdapter = SSO.get().getModuleCfg()
                            .getTokenAttributeAdapter();
                    if (_attributeAdapter != null) {
                        _attributeAdapter.loadAttributes(_token);
                        if (!_token.getAttributes().isEmpty()) {
                            _result.data(_token.getAttributes());
                        }
                    }
                    return _result.toJSON();
                }
            }
        }
        return WebResult.create(ErrorCode.INVALID_PARAMS_VALIDATION).toJSON();
    }
}