package ink.wgink.login.oauth2.server.endpoint;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.Map;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: OauthClientTokenKeyEndpoint
 * @Description: Oauth客户端TokenKey端口
 * @Author: WangGeng
 * @Date: 2020/7/26 9:59 上午
 * @Version: 1.0
 **/
@Controller
public class OAuth2ClientTokenKeyEndpoint {

    protected final Log logger = LogFactory.getLog(getClass());

    @Resource(name = "jwtAccessTokenConverter")
    private JwtAccessTokenConverter converter;

    /**
     * Get the verification key for the token signatures. The principal has to
     * be provided only if the key is secret
     * (shared not public).
     *
     * @param principal the currently authenticated user if there is one
     * @return the key used to verify tokens
     */
    @RequestMapping(value = "/oauth2_client/token_key", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, String> getKey(Principal principal) {
        boolean flag = (principal == null || principal instanceof AnonymousAuthenticationToken) && !converter.isPublic();
        if (flag) {
            throw new AccessDeniedException("您需要进行身份验证才能查看共享密钥");
        }
        Map<String, String> result = converter.getKey();
        return result;
    }


}
