SpringBoot整合OAuth2.0看完你就会了!

这篇具有很好参考价值的文章主要介绍了SpringBoot整合OAuth2.0看完你就会了!。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

OAuth 2.0是一种开放的授权协议,它允许用户授权第三方应用访问其账户(或资源),而无需共享其用户账户凭据。在Spring Boot中,我们可以使用Spring Security的OAuth2.0模块来实现授权验证。

依赖引入

springboot集成oauth2,java知识体系,spring boot,后端,java

配置认证服务器

/**
 * @author Charles
 * @module springboot
 * @since 2023/6/19 16:30
 */

@Configuration
@EnableAuthorizationServer //开启认证服务器
public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    //在 MyOAuth2Config 添加到容器了
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    @Qualifier("jwtTokenStore")
    TokenStore jwtTokenStore;

    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    TokenEnhancerChain tokenEnhancerChain;

    /**
     * 配置被允许访问此认证服务器的客户端详细信息
     * 1.内存管理
     * 2.数据库管理方式
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                //客户端名称
                .withClient("test-pc")
                //客户端密码
                .secret(passwordEncoder.encode("123456"))
                //资源id,商品资源
                .resourceIds("oauth2-server")
                //授权类型, 可同时支持多种授权类型
                .authorizedGrantTypes("authorization_code", "password", "implicit","client_credentials","refresh_token")
                //授权范围标识,哪部分资源可访问(all是标识,不是代表所有)
                .scopes("all")
                //false 跳转到授权页面手动点击授权,true 不用手动授权,直接响应授权码
                .autoApprove(false)
                //客户端回调地址
                .redirectUris("http://www.baidu.com/")
        ;
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //密码模式需要配置认证管理器
        endpoints.authenticationManager(authenticationManager);
        //刷新令牌获取新令牌时需要
        endpoints.userDetailsService(myUserDetailsService);
        endpoints.tokenEnhancer(tokenEnhancerChain);
        //令牌管理策略
//        endpoints.tokenStore(tokenStore);
        //设置为jwt存储
        endpoints.tokenStore(jwtTokenStore);
        endpoints.accessTokenConverter(jwtAccessTokenConverter);
        //授权码管理策略,针对授权码模式有效,会将授权码放到 auth_code 表,授权后就会删除它
        //endpoints.authorizationCodeServices(jdbcAuthorizationCodeServices);
        DefaultTokenServices tokenService = getTokenStore(endpoints);
        endpoints.tokenServices(tokenService);
    }


    //配置TokenService参数
    private DefaultTokenServices getTokenStore(AuthorizationServerEndpointsConfigurer endpoints) {
        DefaultTokenServices tokenService = new DefaultTokenServices();
        tokenService.setTokenStore(endpoints.getTokenStore());
        tokenService.setSupportRefreshToken(true);
        tokenService.setClientDetailsService(endpoints.getClientDetailsService());
        tokenService.setTokenEnhancer(endpoints.getTokenEnhancer());
        //token有效期 1小时
        tokenService.setAccessTokenValiditySeconds(3600);
        //token刷新有效期 15天
        tokenService.setRefreshTokenValiditySeconds(3600 * 12 * 15);
        tokenService.setReuseRefreshToken(false);
        return tokenService;
    }

    /**
     * 解决访问/oauth/check_token 403的问题
     *
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();

    }

配置资源服务器

/**
 * @author Charles
 * @module springboot
 * @since 2023/6/20 12:14
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {


    @Autowired
    @Qualifier("jwtTokenStore")
    TokenStore jwtTokenStore;

    @Override
    public void configure(HttpSecurity http) throws Exception {
          http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //.authorizeRequests(request -> request.anyRequest().access("@checker.check(authentication,request)"))
                //.and()
                //放行
                .antMatchers("/oauth/**","/login/**","/logout/**", "/sse/**").permitAll()
                //其他路径需要role_admin
                .anyRequest().hasAnyAuthority("role_admin")
                .and()
                //表单提交放行
                .formLogin().permitAll()
                .and()
                //csrf关闭
                .exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
              @Override
              public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
                  System.out.println(accessDeniedException);
              }
          });

    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.resourceId("oauth2-server")
                 .tokenServices(tokenDefaultServices());
    }


    /**
     * 配置资源服务器如何校验token
     * 1. DefaultTokenServices
     * 如果认证服务器和资源服务器在同一个服务,则直接采用默认服务验证
     * 2.RemoteTokenServices
     * 当认证服务器和资源服务器不在同一个服务,要使用此服务器去远程认证服务器验证
     * @return
     */
    @Primary
    @Bean
    public DefaultTokenServices tokenDefaultServices() {
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(jwtTokenStore);
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }

//    @Primary
//    @Bean
//    public RemoteTokenServices tokenServices() {
//        //资源服务器去远程认证服务器验证 token 是否有效
//        final RemoteTokenServices tokenService = new RemoteTokenServices();
//        //请求认证服务器验证URL,注意:默认这个端点是拒绝访问的,要设置认证后可访问
//        tokenService.setCheckTokenEndpointUrl("http://localhost:8899/oauth/check_token");
//        //在认证服务器配置的客户端id
//        tokenService.setClientId("test-pc");
//        //在认证服务器配置的客户端密码
//        tokenService.setClientSecret("123456");
//        return tokenService;
//    }
}

token配置

/**
 * @author Charles
 * @module springboot
 * @since 2023/6/20 15:25
 */

@Configuration
public class JwtTokenStoreConfig {

    @Autowired
    private CustomTokenEnhancer customTokenEnhancer;


    @Value("${privateKey}")
    private String privateKey;

    @Value("${password}")
    private String password;

    @Value("${alias}")
    private String alias;

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter(){
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource(privateKey), password.toCharArray());
        jwtAccessTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair(alias));
        return jwtAccessTokenConverter;
    }

    @Bean("jwtTokenStore")
    public TokenStore jwtTokenStore(){
        JwtTokenStore jwtTokenStore = new JwtTokenStore(jwtAccessTokenConverter());
        return jwtTokenStore;
    }


    @Bean
    public TokenEnhancerChain tokenEnhancerChain() {
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancers = new ArrayList<>();
        enhancers.add(jwtAccessTokenConverter());
        enhancers.add(customTokenEnhancer);
        //将自定义Enhancer加入EnhancerChain的delegates数组中
        enhancerChain.setTokenEnhancers(enhancers);
        return enhancerChain;
    }


    private static final KeyStore JKS_STORE;

    static {
        try {
            JKS_STORE = KeyStore.getInstance("jks");
        } catch (KeyStoreException e) {
            throw new RuntimeException("can not obtain jks keystore instance");
        }
    }

    @Bean
    @ConditionalOnMissingBean
    @SneakyThrows
    public JWKSource<SecurityContext> jwkSource() {
        ClassPathResource classPathResource = new ClassPathResource(privateKey);
        char[] pin = password.toCharArray();
        JKS_STORE.load(classPathResource.getInputStream(), pin);
        RSAKey rsaKey = RSAKey.load(JKS_STORE, alias, pin);
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

配置UserDetailsService

/**
 * @author Charles
 * @module springboot
 * @since 2023/6/20 11:47
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return new User("admin", passwordEncoder.encode("123456"),
                AuthorityUtils.createAuthorityList("role_admin"));
    }
}

好了到此为止,以上就是springboot整合ouath2.0的主要代码啦,欢迎大家在评论区留言讨论!文章来源地址https://www.toymoban.com/news/detail-736885.html

到了这里,关于SpringBoot整合OAuth2.0看完你就会了!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • AI绘画是什么软件?看完你就知道了

    你们知道吗?AI绘画软件其实是通过AI技术,绘画出不同风格的画,让大家都可以根据自己的需求画出漂亮的图片;它还可以描述出自己想象的场景,并添加一张参考图,随后便自动生成画作,那么你们知道智能AI绘画免费软件有哪些吗?如果还不是很了解的话,那就跟着我一

    2024年02月11日
    浏览(37)
  • 手机扫描怎么做成文档?看完你就学会操作了

    相信很多职场人在办公的时候,经常会遇到大量的文件需要处理,其中一部分可能是纸质版的文件。但为了方便进行编辑,大家需要可以借助一些扫描软件对纸质版文件进行扫描,但是还有一部分小伙伴可能还不知道应该怎么进行操作。 今天就给大家带来三种较为简单的方法

    2024年02月08日
    浏览(35)
  • ai绘画图片美女怎么画?看完你就知道了

    大家在刚开始接触文生图的AI绘画的时候,是不是会因为在输入描述词时不知道应该如何描述,而导致生成的图片都比较简单或者混乱,不符合自己的预期。 其实,我刚接触AI绘图也是这样的,不过经过我的探索,我用AI做的图越来越漂亮了,给大家欣赏一下。 那么大家想知

    2024年02月14日
    浏览(30)
  • 月薪6000在中国什么水平?看完你就不焦虑了

    今天刷到一个很扎心的问题:你对自己现在的收入满意吗? 多数人都是不假思索地反问:“怎么会满意……” 都说挣钱够用就行,谁又真正满意过。 镜头前的主播抱怨忙,却偷偷年收百万,00后副业月入10万,连知根知底的发小,也突然月入过万。 而你拼命不比谁少, 跑进

    2023年04月22日
    浏览(29)
  • 无线路由器为什么需要重启 看完你就知道

    无线路由器已经成为每个家庭中不可或缺的网络设备。使用WiFi网络,无论是上网刷微博,还是在线追剧,亦或是进行在线游戏,经常卡顿的现象是最让人受不了的。有时候WiFi连接不佳,拍两下路由器是没有效果的。我们会重启无线路由器,重启后明显会感觉的网络变得流畅

    2024年02月05日
    浏览(37)
  • 【Unity】Time.deltaTime有什么用?看完你就明白

    大多数刚开始使用 Unity 的人(包括我),都会对 Time.deltaTime 感到迷惑。 看完本文,你就会明白 Time.deltaTime的定义及作用。 根据定义, Time.deltaTime是每一帧之间的时间间隔 (以秒为单位)。 这有助于我们使游戏与帧数无关,也就是说,无论 fps 是多少,游戏都将以相同的速

    2024年02月16日
    浏览(32)
  • 记录--组件阅后即焚?挂载即卸载!看完你就理解了

    上家公司有个需求是批量导出学生的二维码,我一想这简单啊,不就是先批量获取学生数据,然后根据 QRcode 生成二维码,然后在用 html2canvas 导出成图片嘛。 由于公司工具库有现成的生成压缩包方法,我只需要获得对应的图片 blob 就可以了,非常的easy啊。 思路没啥问题,但

    2024年02月05日
    浏览(27)
  • 电脑技巧:电脑关机、休眠、睡眠之间如何选择,看完你就懂了

    目录 一、关机、休眠、睡眠的区别? 1.关机 2.休眠   休眠的优点 休眠的缺点 3.睡眠   睡眠的优点 睡眠的缺点 二、什么时候关机/休眠/睡眠? 什么时候需要关机?  什么情况下使用休眠模式? 什么情况下使用睡眠模式? 三、终极建议 电脑技巧:电脑关机、休眠、睡眠之

    2024年01月15日
    浏览(36)
  • springboot整合springsecurity+oauth2.0密码授权模式

    本文采用的springboot去整合springsecurity,采用oauth2.0授权认证,使用jwt对token增强。本文仅为学习记录,如有不足多谢提出。 OAuth 2.0是用于授权的行业标准协议。OAuth 2.0为简化客户端开发提供了特定的授权流,包括Web应用、桌面应用、移动端应用等。 Resource owner(资源拥有者)

    2024年02月04日
    浏览(39)
  • 网上宣传的0月租流量卡是骗局吗?看完你就知道了!

    大家一定要清楚一件事,目前三大运营商并没有推出0月租流量卡,正规号卡都是有月租的,每月按时扣费。 而网上所谓的0月租流量卡其实都是“物联卡”,又被 称为“纯流量卡”。 说到物联卡,除了是0月租外,还有一个明显的特点,就是功能单一,没有手机号不能注册,

    2024年02月13日
    浏览(29)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包