AuthChecker.java 2.4 KB
Newer Older
智布道's avatar
智布道 已提交
1 2 3
package me.zhyd.oauth.utils;

import me.zhyd.oauth.config.AuthConfig;
4
import me.zhyd.oauth.config.AuthSource;
5
import me.zhyd.oauth.exception.AuthException;
智布道's avatar
智布道 已提交
6
import me.zhyd.oauth.model.AuthResponseStatus;
智布道's avatar
智布道 已提交
7 8

/**
智布道's avatar
智布道 已提交
9 10
 * 授权配置类的校验器
 *
智布道's avatar
智布道 已提交
11 12 13
 * @author yadong.zhang (yadong.zhang0415(a)gmail.com)
 * @since 1.8
 */
14
public class AuthChecker {
智布道's avatar
智布道 已提交
15 16

    /**
智布道's avatar
智布道 已提交
17
     * 是否支持第三方登录
智布道's avatar
智布道 已提交
18
     *
19
     * @param config config
20
     * @param source source
智布道's avatar
智布道 已提交
21 22
     * @return true or false
     */
23 24 25 26 27
    public static boolean isSupportedAuth(AuthConfig config, AuthSource source) {
        boolean isSupported = StringUtils.isNotEmpty(config.getClientId()) && StringUtils.isNotEmpty(config.getClientSecret()) && StringUtils.isNotEmpty(config.getRedirectUri());
        if (isSupported && AuthSource.ALIPAY == source) {
            isSupported = StringUtils.isNotEmpty(config.getAlipayPublicKey());
        }
28 29 30
        if (isSupported && AuthSource.STACK_OVERFLOW == source) {
            isSupported = StringUtils.isNotEmpty(config.getStackOverflowKey());
        }
31 32 33 34 35 36 37 38 39
        return isSupported;
    }

    /**
     * 检查配置合法性。针对部分平台, 对redirect uri有特定要求。一般来说redirect uri都是http://,而对于facebook平台, redirect uri 必须是https的链接
     *
     * @param config config
     * @param source source
     */
40
    public static void checkConfig(AuthConfig config, AuthSource source) {
41 42
        String redirectUri = config.getRedirectUri();
        if (!GlobalAuthUtil.isHttpProtocol(redirectUri) && !GlobalAuthUtil.isHttpsProtocol(redirectUri)) {
智布道's avatar
智布道 已提交
43
            throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI);
44
        }
45
        // facebook的回调地址必须为https的链接
46
        if (AuthSource.FACEBOOK == source && !GlobalAuthUtil.isHttpsProtocol(redirectUri)) {
智布道's avatar
智布道 已提交
47
            throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI);
48
        }
49 50
        // 支付宝在创建回调地址时,不允许使用localhost或者127.0.0.1
        if (AuthSource.ALIPAY == source && GlobalAuthUtil.isLocalHost(redirectUri)) {
智布道's avatar
智布道 已提交
51
            throw new AuthException(AuthResponseStatus.ILLEGAL_REDIRECT_URI);
52
        }
智布道's avatar
智布道 已提交
53
    }
54 55 56 57 58 59 60 61

    /**
     * 校验回调传回的code
     *
     * @param code 回调时传回的code
     */
    public static void checkCode(String code) {
        if (StringUtils.isEmpty(code)) {
智布道's avatar
智布道 已提交
62
            throw new AuthException(AuthResponseStatus.ILLEGAL_CODE);
63 64
        }
    }
智布道's avatar
智布道 已提交
65
}