一、错误描述
项目OAuth2安全框架认证,使用postman工具测试post接口,报403 Forbidden错误提示 - “ Similar to 403 Forbidden, but specifically for use when authentication is possible but has failed or not yet been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the requested resource.”,如下图
二、解决方法
1、项目配置Oauth2注入配置,可以跳过接口认证,参考代码如下
package com.nacos.config;@b@@b@import org.springframework.context.annotation.Configuration;@b@import org.springframework.security.crypto.password.NoOpPasswordEncoder;@b@import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;@b@import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;@b@import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;@b@import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;@b@@b@/**@b@ * @b@ * * @author jun.ni @b@ * * @version 1.0.0 @b@ * * @ClassName OAuth2AuthorizationServer.java @b@ * * @Description TODO @b@ * * @createTime 2022/6/29 11:27 @b@ * https://blog.csdn.net/qq_40555976/article/details/106642882@b@ */@b@@Configuration@b@@EnableAuthorizationServer@b@public class OAuth2AuthorizationServer extends AuthorizationServerConfigurerAdapter {@b@@b@ @Override@b@ public void configure(ClientDetailsServiceConfigurer clients) throws Exception {@b@ clients.inMemory()@b@ // 客户端id@b@ .withClient("client")@b@ // 客户端密钥@b@ .secret("123456")@b@ // 权限@b@ .scopes("admin","user")@b@ // 获取授权码后重定向地址@b@ .redirectUris("http://baidu.com")//localhost:9001/admin/aa@b@ // 授权码和刷新token@b@ .authorizedGrantTypes("authorization_code","refresh_token");@b@ }@b@@b@ @Override@b@ public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {@b@ security.tokenKeyAccess("permitAll()");@b@ security.checkTokenAccess("isAuthenticated()");@b@ security.allowFormAuthenticationForClients();@b@ //解决Encoded password does not look like BCrypt报错@b@ //因为springsecurity在最新版本升级后,默认把之前的明文密码方式给去掉了@b@ //https://spring.io/blog/2017/11/01/spring-security-5-0-0-rc1-released#password-storage-updated@b@ security.passwordEncoder(NoOpPasswordEncoder.getInstance());@b@ }@b@}
2、重启项目,postman测试正常,如下图