oauth/token 访问此资源需要完全身份验证

2024-01-28

我想以用户身份登录,但由于某种原因,端点似乎oauth/token受到保护:

Request URL:http://192.168.0.14:8080/oauth/token
Request Method:POST
Status Code:401 
Remote Address:192.168.0.14:8080
Referrer Policy:no-referrer-when-downgrade
Access-Control-Allow-Headers:x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN
Access-Control-Allow-Methods:PATCH,POST,GET,OPTIONS,DELETE
Access-Control-Allow-Origin:*
Access-Control-Max-Age:3600
Cache-Control:no-store
Cache-Control:no-cache, no-store, max-age=0, must-revalidate
Content-Type:application/json;charset=UTF-8
Date:Tue, 06 Mar 2018 18:59:25 GMT
Expires:0
Pragma:no-cache
Pragma:no-cache
Transfer-Encoding:chunked
WWW-Authenticate:Bearer realm="testjwtresourceid", error="unauthorized", error_description="Full authentication is required to access this resource"
WWW-Authenticate:Basic realm="oauth2/client"
X-Content-Type-Options:nosniff
X-Frame-Options:DENY
X-XSS-Protection:1; mode=block

有趣的是......我收到这条消息:

2018-03-06 19:59:25.766  WARN 31030 --- [nio-8080-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder     : Encoded password does not look like BCrypt

似乎出于某种原因,整个事情贯穿了BasicAuthenticationFilter。很明显,这看起来不像 BCrypt .. 尽管我将 BCrypt 设置为我的密码编码器:

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    auth.authenticationProvider(daoAuthenticationProvider());
}

/**
 * Using {@link BCryptPasswordEncoder} for user-password encryption.
 * @return
 */
@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

看起来像WebSecurity尝试使用 BCrypt O_o 对客户端机密进行编码

security.jwt.client-id=CLIENT_ID
security.jwt.client-secret=CLIENT_SECRET

整个网络配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${security.signing-key}")
    private String signingKey;

    @Value("${security.encoding-strength}")
    private Integer encodingStrength;

    @Value("${security.security-realm}")
    private String securityRealm;

    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * Nothing to configure yet.
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception { }

    /**
     * Define routes for {@link WebSecurity}.
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {

        final String[] SWAGGER_UI = {
                "/swagger-resources/**",
                "/swagger-ui.html",
                "/v2/api-docs",
                "/webjars/**"
        };

        web.ignoring().antMatchers("/pub/**", "/users")
                .antMatchers(SWAGGER_UI);
    }

    @Bean
    public JwtAccessTokenConverter accessTokenConverter() {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey(signingKey);
        return converter;
    }

    /**
     * Using {@link JwtTokenStore} for JWT access tokens.
     * @return
     */
    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(accessTokenConverter());
    }

    /**
     * Provide {@link DefaultTokenServices} using the {@link JwtTokenStore}.
     * @return
     */
    @Bean
    public DefaultTokenServices tokenServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

    /**
     * We provide the AuthenticationManagerBuilder using our {@link UserDetailsService} and the {@link BCryptPasswordEncoder}.
     * @param auth
     * @throws Exception
     */
    @Autowired
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()).and()
            .authenticationProvider(daoAuthenticationProvider());
    }

    /**
     * Using {@link BCryptPasswordEncoder} for user-password encryption.
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * Provide {@link DaoAuthenticationProvider} for password encoding and set the {@link UserDetailsService}.
     * @return
     */
    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(this.userDetailsService);
        return daoAuthenticationProvider;
    }

}

OAuth 配置

@Configuration
@EnableAuthorizationServer
@EnableResourceServer
public class OAuth2Configuration extends AuthorizationServerConfigurerAdapter {

    @Configuration
    @EnableResourceServer
    public class ResourceServer extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .requestMatchers().antMatchers("/**")
                    .and()
                    .authorizeRequests().anyRequest().access("#oauth2.hasScope('write')");
        }

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
            resources.resourceId(resourceIds);
        }

    }

    @Value("${security.jwt.client-id}")
    private String clientId;

    @Value("${security.jwt.client-secret}")
    private String clientSecret;

    @Value("${security.jwt.grant-type}")
    private String grantType;

    @Value("${security.jwt.scope-read}")
    private String scopeRead;

    @Value("${security.jwt.scope-write}")
    private String scopeWrite;

    @Value("${security.jwt.resource-ids}")
    private String resourceIds;

    @Autowired
    private TokenStore tokenStore;

    @Autowired
    private JwtAccessTokenConverter accessTokenConverter;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(ClientDetailsServiceConfigurer configurer) throws Exception {
        configurer
                .inMemory()
                .withClient(clientId)
                .secret(clientSecret)
                .authorizedGrantTypes(grantType)
                .scopes(scopeRead, scopeWrite)
                .resourceIds(resourceIds);
    }


    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        enhancerChain.setTokenEnhancers(Arrays.asList(accessTokenConverter));
        endpoints.tokenStore(tokenStore)
                .accessTokenConverter(accessTokenConverter)
                .tokenEnhancer(enhancerChain)
                .authenticationManager(authenticationManager);
    }

}

因为您创建了以下 Bean,所以所有安全配置都将使用此PasswordEncoder。就您而言,网络安全和授权服务器安全。

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

我很确定你的security.jwt.client-secret是纯文本。

因此,发生的情况是,当您发出请求时,您的 AuthorizationSecurityConfig 尝试读取security.jwt.client-secret作为 BCrypt 编码的字符串,但最终它不是。

因此,整个身份验证过程失败并记录警告消息。

要解决此问题,您有两种选择:

First:

配置要使用的 AuthorizationSecurityNoOpPasswordEncoder。以下是您可以覆盖此设置的方法。提个醒NoOpPasswordEncoder已被弃用。

@Override
public void configure(final AuthorizationServerSecurityConfigurer security) throws Exception {
    security.passwordEncoder(NoOpPasswordEncoder.getInstance());
}

Second(首选):

生成您的 BCrypt 值security.jwt.client-secret并将其设置在您的application.properties/yaml.

谢谢David https://stackoverflow.com/users/5613927/david-steiman谁消除了对a的疑问类似的答案在这里 https://stackoverflow.com/a/40761409/979772.

你猜怎么着,当我寻找这个问题的解决方案时,我遇到了同样的问题。 :-)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

oauth/token 访问此资源需要完全身份验证 的相关文章

随机推荐

  • 在 .NET Core 中使用 SHA-1

    在 dotnet core 中对字符串进行哈希处理时 我得到了奇怪的结果 我发现了这个类似的问题 使用 ASP NET Core 计算 SHA1 https stackoverflow com questions 35363358 comp
  • sqlite,从另一个表中的列更新列

    我目前正在处理更新的查询table1 state从数据中table2 state基于两个表中的城市字段 换句话说 当表 1 和表 2 中的城市字段匹配时 用表 2 中的州更新表 1 我遇到的问题是 当没有城市匹配时 会随机添加一个州 例如爱
  • 真的需要通配符泛型吗?

    例如 public String add Set gt 这是一个列表的列表 该方法可以向其中添加不同组件类型的列表 public void foo List
  • 在后台脚本中设置间隔

    我正在为实时产品开发浏览器扩展 我有一个在manifest json 中设置了 persistent true 的背景页面 我使用的是v2 版本 我使用 setInterval 每秒不断地轮询服务器以获取新数据 后台脚本还会缓存迄今为止收集
  • 使用纯 R 通过 dbplyr 处理日期

    dbplyr 将 dplyr 和基本 R 命令转换为 SQL 以便开发人员可以编写 R 代码并在数据库中执行它 整洁宇宙参考 https dbplyr tidyverse org 在 R 中处理日期时 通常使用 lubridate 包 然而
  • JDK 11 + JUnit 5 + Jigsaw:Junit 无法运行“模块信息”测试

    我尝试在 Gradle 项目中使用 JUnit 5 compileJava and compileTestJava两者都成功了 但是test失败并显示奇怪的消息Could not execute test class module info
  • 从“dragmove”回调中移动图层后,事件丢失

    我有一个移动图层的滚动条 因此该图层在滚动条的 dragmove 回调中移动 这会导致所有绑定事件在移动的图层上断开连接 请看这个小提琴 http jsfiddle net NY4QK 10 http jsfiddle net NY4QK
  • 链接 2 个异步调用(promise API)以串行运行

    这与我发布的问题类似today https stackoverflow com questions 16307652 promise api combining results of 2 asynchronous call 但需要串行链接请
  • 更新 Jupyter Notebook 扩展的正确方法是什么?

    升级 Jupyter Notebook 扩展 例如 RISE ipywidgets 的正确方法是什么 我有一个例程 可以通过运行来更新我的 Python 包pip install upgrade 并且当新的笔记本扩展版本可用时 这也会下载并
  • 如何将日期和时间分成两个元素?

    我制作了一个实时显示日期和时间的对象 我想知道如何将时间部分与日期分开 以便我可以将它放在自己的 HTML 元素中 以便我可以对其应用不同的样式 我对 JavaScript 不太熟悉 而且我发现使用日期对象非常复杂 LiveDateTime
  • 将最近的提交移至不同的现有分支

    我刚刚对功能分支进行了一些更改 但我意识到我在错误的分支上 如何获取我所做的最后一次提交 并将其移动到另一个已经存在的分支 我还没有推任何东西 我见过一些类似的问题 但它们都涉及创建一个新分支 并且他们所做的所有硬头重置都令人恐惧 git
  • 如何减少简单选择查询的响应时间?

    MarketPlane表包含超过 6000 万行 当我需要特定日期的飞机总数时 我执行此查询需要 7 分钟以上 我怎样才能减少这个时间 SELECT COUNT primaryKeyColumn FROM MarketPlan WHERE
  • jspc-maven-plugin 未执行?

    我在我的 pom xml 中添加了这样的 jspc 插件
  • Oracle:如何以最佳方式使用不同的 where 子句进行多次计数?

    我需要对同一表中具有不同 where 子句的行进行计数 以下是我所需的输出 Bu A B C D E F G H J K L M N GB01 267 284 84 45 35 32 458 801 111 899 892 56 99 NL
  • WooCommerce:自动完成付款订单

    通常 wooCommerce 应自动完成虚拟产品的订单 但事实并非如此 这是一个真正的问题 甚至是一个BUG之类的 所以此时你可以找到一些有用的东西 但不是很方便 1 一段代码 您可以在 wooCommerce 文档中找到 Auto Com
  • 为复杂嵌套数据编写 REST API

    因此 我正在 Angular 中构建一个应用程序 该应用程序将在后面利用 REST API 在 Node 上运行 我在设计此 API 时在处理数据复杂性方面遇到一些麻烦 需要一些帮助 以下是有问题的不同资源 医生 每个医生可能有多个患者 患
  • 在Excel VBA中,如何检查网页是否完全加载?

    为了暂停代码直到网页完全加载 我几乎一直在使用下面的方法并取得了巨大的成功 Do While objIE Busy True Or objIE readyState lt gt 4 DoEvents Loop 但有时 我会看到文本内容在该方
  • Flowtype 不断需要空检查

    我想知道如何避免这些大量的空检查 或者至少了解重点是什么 因为它似乎适得其反 如果我省略空检查 Flowtype 会给我一个错误 var myEl new MyElement if document body null error on n
  • Scrapy 使用 selenium,webdriver 无法实例化

    我正在尝试将 selenium phantomjs 与 scrapy 一起使用 但我遇到了很多错误 例如 采用以下代码片段 def parse self resposne while True try driver webdriver Ph
  • oauth/token 访问此资源需要完全身份验证

    我想以用户身份登录 但由于某种原因 端点似乎oauth token受到保护 Request URL http 192 168 0 14 8080 oauth token Request Method POST Status Code 401