加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 获取访问令牌需要身份验证(不允许匿名)

发布时间:2020-12-15 00:36:12 所属栏目:Java 来源:网络整理
导读:我尝试修改现有的例子 – Tonr2 and Sparklr2. 此外,我根据Spring Boot Spring Boot OAuth2查看了本教程.我尝试在Tonr2示例中构建应用程序,但没有首次登录(在tonr2上).我只需要在Sparklr2端进行一次身份验证.我这样做: @Bean public OAuth2ProtectedResourc
我尝试修改现有的例子 – Tonr2 and Sparklr2.
此外,我根据Spring Boot Spring Boot OAuth2查看了本教程.我尝试在Tonr2示例中构建应用程序,但没有首次登录(在tonr2上).我只需要在Sparklr2端进行一次身份验证.我这样做:
@Bean
    public OAuth2ProtectedResourceDetails sparklr() {
        AuthorizationCodeResourceDetails details = new AuthorizationCodeResourceDetails();
        details.setId("sparklr/tonr");
        details.setClientId("tonr");
        details.setTokenName("oauth_token");
        details.setClientSecret("secret");
        details.setAccessTokenUri(accessTokenUri);
        details.setUserAuthorizationUri(userAuthorizationUri);
        details.setScope(Arrays.asList("openid"));
        details.setGrantType("client_credentials");
        details.setAuthenticationScheme(AuthenticationScheme.none);
        details.setClientAuthenticationScheme(AuthenticationScheme.none);
        return details;
    }

但我需要身份验证才能获得访问令牌(匿名不允许).我检查了this question.当然,我的用户是匿名的 – 我想登录Sparklr2.此外,我尝试了这种bean的不同设置组合,但没有什么好处.怎么解决?如何使它按我想要的方式工作?

解决方法

这篇文章差不多两年了.

从AccessTokenProviderChain抛出异常

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        if (auth instanceof AnonymousAuthenticationToken) {
            if (!resource.isClientOnly()) {
                throw new InsufficientAuthenticationException(
                    "Authentication is required to obtain an access token (anonymous not allowed)");
            }
        }

你要么

>在OAuth2RestTemplate中使用ClientCredentialsResourceDetails,或
>在使用AuthorizationCodeResourceDetails访问外部资源之前对用户进行身份验证

事实上,在tonr2和sparklr2示例中(我个人觉得这个名字非常混乱),要访问sparklr2上的资源,用户必须首先在tonr2上进行身份验证.如oauth2/tonr所示:

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().withUser("marissa").password("wombat").roles("USER").and().withUser("sam")
            .password("kangaroo").roles("USER");
}

如果您的用户是匿名用户,您可能需要检查Single Sign On.

对于只想快速尝试Oauth2集成的人,请在您的应用程序中添加基本身份验证:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .anyRequest().authenticated().and().httpBasic();
}

application.properties:

spring.security.user.password=password
spring.security.user.name=user

不要忘记在项目中添加spring-boot-starter-security.

例如在gradle中:编译’org.springframework.boot:spring-boot-starter-security’

或者您也可以通过以下方式禁用AnonymousAuthenticationToken:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.anonymous().disable();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读