• 手机版

    扫码体验手机版

  • 微信公众号

    扫码关注公众号

国内首家协议开发

软芯音视解码保护平台

在线
客服

发布
需求

在线
聊天

天盟
APP

天盟APP下载

关注
微信

微信扫一扫访问
顶部

原生方式搭建基于spring security oauth2(不使用springboot),无法跳转认

client端配置代码:
@EnableOAuth2Client
@Configuration
@Component
public class Oauth2ClientConfig {

    private final static Logger logger = LoggerFactory.getLogger(Oauth2ClientConfig.class);

    private static String location = "classpath:config/*/oauth.properties";

    private static Map oauthInfo = new HashMap();

    @Autowired
    private OAuth2ClientContext oauth2Context;

    /**
     * 获取配置文件信息
     */
    static {
        ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources;
        try {
            resources = patternResolver.getResources(location);
            location = resources[0].getFile().getAbsolutePath();
            logger.info("location" + location);
            Properties props = new Properties();
            try {
                if (location.contains("dev")) {
                    props = PropertiesLoaderUtils.loadAllProperties("config/dev/oauth.properties");
                } else if (location.contains("test")) {
                    props = PropertiesLoaderUtils.loadAllProperties("config/test/oauth.properties");
                } else if (location.contains("production")) {
                    props = PropertiesLoaderUtils.loadAllProperties("config/production/oauth.properties");
                }
                for (Object key : props.keySet()) {
                    //logger.warn(key + " : " + (String) props.get(key));
                    oauthInfo.put((String) key, (String) props.get(key));
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Bean
    public AccessTokenRequest accessTokenRequest() {
        AccessTokenRequest defaultAccessTokenRequest = new DefaultAccessTokenRequest();
        Map headers = new HashMap();
        List headerList = new ArrayList();
        headerList.add("Basic " + oauthInfo.get("public_key"));
        headers.put("Authorization", headerList);
        defaultAccessTokenRequest.setHeaders(headers);
        defaultAccessTokenRequest.setCurrentUri(oauthInfo.get("redirect_uri"));
        return defaultAccessTokenRequest;
    }

    @Bean
    public OAuth2RestTemplate oAuth2RestTemplate() {
        accessTokenRequest().setPreservedState(oauthInfo.get("redirect_uri"));
        accessTokenRequest().setStateKey(new DefaultStateKeyGenerator().generateKey(resourceDetails()));

        AuthorizationCodeAccessTokenProvider provider = new AuthorizationCodeAccessTokenProvider();
        provider.setAuthenticationHandler(new ClientAuthenticationHandler() {
            @Override
            public void authenticateTokenRequest(
                    OAuth2ProtectedResourceDetails resource,
                    MultiValueMap form, HttpHeaders headers) {
                headers.set("Authorization", "Basic " + oauthInfo.get("private_key"));
            }
        });
        AccessTokenProviderChain providerChain = new AccessTokenProviderChain(Arrays.asList(provider));
        //oauth2Context.setPreservedState(accessTokenRequest().getStateKey(),accessTokenRequest().getPreservedState());
        OAuth2RestTemplate template = new OAuth2RestTemplate(resourceDetails(), oauth2Context);
        template.setAccessTokenProvider(providerChain);
        return template;
    }

    @Bean
    public AuthorizationCodeResourceDetails resourceDetails() {
        AuthorizationCodeResourceDetails resource = new AuthorizationCodeResourceDetails();
        resource.setClientSecret(oauthInfo.get("client_secret"));
        resource.setAccessTokenUri(oauthInfo.get("oauth_url") + oauthInfo.get("request_and_refresh_token"));
        resource.setClientId(oauthInfo.get("client_id"));
        resource.setGrantType("authorization_code");
        resource.setUserAuthorizationUri(oauthInfo.get("oauth_url") + oauthInfo.get("request_code_url"));
        resource.setScope(Arrays.asList("all"));
        resource.setPreEstablishedRedirectUri(oauthInfo.get("redirect_uri"));
        return resource;
    }

    @Bean
    public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter(OAuth2RestTemplate oauth2RestTemplate,
                                                                                                   RemoteTokenServices tokenService) {
        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter("/login");
        filter.setRestTemplate(oauth2RestTemplate);
        filter.setTokenServices(tokenService);

        //设置回调成功的页面
        filter.setAuthenticationSuccessHandler(new SimpleUrlAuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                this.setDefaultTargetUrl("/home");
                super.onAuthenticationSuccess(request, response, authentication);
            }
        });
        return filter;

    }

    @Bean
    public RemoteTokenServices tokenService(OAuth2ProtectedResourceDetails details) {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl("checkTokenUrl");
        tokenService.setClientId(details.getClientId());
        tokenService.setClientSecret(details.getClientSecret());
        return tokenService;
    }
}
配置文件:
client_id=clinet2
client_secret=clinet2
#公钥(BASE64(xx))
public_key=Y2xpZW50MjpjbGllbnQy
#私钥(BASE64(xx))
private_key=Y2xpZW50MjpjbGllbnQy
#spring oauth2.0服务url
#oauth_url=http://127.0.0.1:8080/server
oauth_url=http://127.0.0.1:9999/server
#获取请求code URL
request_code_url=/oauth/authorize
#获取请求token或刷新token URL
request_and_refresh_token=/oauth/token
#回调地址
redirect_uri=http://www.baidu.com
#jwt秘钥地址
token_key_uri=/oauth/token_key


基于springboot的使用@EnableOAuth2Sso注解已实现跳转,但原生却死活不行,快崩溃了

免责声明:本内容仅代表回答会员见解不代表天盟观点,请谨慎对待。

版权声明:作者保留权利,不代表天盟立场。

使用道具 举报

发新帖

发布任务需求已有1031167位用户正在使用天盟网服务

发布分类: *
任务预算: *
需求内容: *
手机号码: *
任务商家报价为
  • 预算价 :
  • 成交价 :
  • 完工期 :
  • 质保期 :

* 最终任务项目以服务商报价、双方协商为准!