spring security 和OAuth2 整合访问 localhost:8082/oauth/token 报401的问题,或者403的问题

 @Bean
    public PasswordEncoder passwordEncoder() {
        /**
         * 采坑
         * spring-boot2 之后废弃了MD5,使用BCryptPasswordEncoder()加密;
         *
         */
     return new BCryptPasswordEncoder();

}

注意在security的配置内中,要使用BCryptPasswordEncoder 加密,不能使用自己实现的md5加密.(springboot2以上版本)

 

同时在Auth的配置内中配置secret也要加密BCryptPasswordEncoder

@Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient(clientOauthDataConfiguration.getClientId())
                .secret(passwordEncoder.encode(clientOauthDataConfiguration.getSecret())) //客服端安全码
                .authorizedGrantTypes(clientOauthDataConfiguration.getGrantTypes()) //授权类型
                .accessTokenValiditySeconds(clientOauthDataConfiguration.getTokenValidityTime()) //token有效期
                .refreshTokenValiditySeconds(clientOauthDataConfiguration.getRefreshTokenValidityTime()) //刷新token有效期
                .scopes(clientOauthDataConfiguration.getScopes()); //客户端范围
    }

 

最后注意,保存在数据库中的用户密码也要用BCryptPasswordEncoder这个加密

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个简单的 Spring SecurityOAuth2 的整合项目案例: 1. 首先,在 pom.xml 中添加以下依赖: ``` <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> <version>2.1.2.RELEASE</version> </dependency> ``` 2. 在 Spring Security 的配置文件中添加以下代码: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and().csrf().disable() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("resource_id").stateless(true); } } ``` 3. 在 application.yml 中添加以下配置: ``` security: oauth2: client: client-id: client client-secret: secret access-token-uri: http://localhost:8080/oauth/token user-authorization-uri: http://localhost:8080/oauth/authorize resource: user-info-uri: http://localhost:8080/user/me ``` 4. 创建一个控制器类,用于处理 OAuth2 的回调请求: ``` @RestController @RequestMapping("/api") public class ApiController { @GetMapping("/user") public String getUserInfo(@AuthenticationPrincipal OAuth2User user) { return user.getName(); } } ``` 5. 最后,启动应用程序并访问 http://localhost:8080/api/user,应该会跳转到 OAuth2 的授权页面,完成授权后应该能够看到当前用户的信息。 以上就是一个简单的 Spring SecurityOAuth2 的整合项目案例,希望能对你有所帮助。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值