oauth2.0的配置信息AuthorizationServerConfigurerAdapter

继承AuthorizationServerConfigurerAdapter方法的配置

@Configuration
@EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;  //加密

    @Autowired
    private UserServiceImpl userDetailsService;  //加载用户信息

    @Autowired
    private AuthenticationManager authenticationManager; //认证管理器

    @Autowired
    private TokenStore tokenStore;  //JWT令牌存储方案

    @Autowired
    private DataSource dataSource; //数据源,用于从数据库获取数据进行认证操作,测试可以从内存中获取

    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;  //jwt设置需要的字段

    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;  //jks公钥

    @Autowired
    private AuthorizationCodeServices authorizationCodeServices;  //授权码

    @Autowired
    private ClientDetailsService clientDetailsService;  //将客户端client id secret这些信息存储到数据库

    @Bean  //设置授权码模式的授权码如何存取
    public AuthorizationCodeServices authorizationCodeServices(DataSource dataSource) {
        return new JdbcAuthorizationCodeServices(dataSource);
    }

    @Bean  //客户端配置,将客户端client id secret这些信息存储到数据库
    public ClientDetailsService clientDetailsService() {
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean  //令牌管理服务
    public AuthorizationServerTokenServices tokenService() {
        //jwt令牌内容增强
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> delegates = new ArrayList<>();
        delegates.add(jwtTokenEnhancer);
        delegates.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(delegates); //配置JWT的内容增强器
        // 配置tokenServices参数
        DefaultTokenServices service=new DefaultTokenServices();
        service.setClientDetailsService(clientDetailsService); //客户端详情服务
        service.setSupportRefreshToken(true); //支持刷新令牌

        service.setTokenStore(tokenStore); //令牌存储,把access_token和refresh_token保存到数据库
        service.setTokenEnhancer(enhancerChain); //配置JWT的内容增强

        service.setAccessTokenValiditySeconds(7200);  // 令牌默认有效期2小时
        service.setRefreshTokenValiditySeconds(259200);  // 刷新令牌默认有效期3天
        return service;
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clientsDetails) throws Exception {
        //从数据库加载认证信息
        clientsDetails.withClientDetails(clientDetailsService);
/*        // 测试用,将客户端信息存储在内存中
        clientsDetails.inMemory()
                .withClient("client")   // client_id
                .secret(bCryptPasswordEncoder.encode("123456"))       // client_secret
                .authorizedGrantTypes("password", "authorization_code", "refresh_token")     // 该client允许的授权类型
                .scopes("all")     // 允许的授权范围
                .accessTokenValiditySeconds(3600)
                .refreshTokenValiditySeconds(86400)
                //加上验证回调地址
                .redirectUris("http://www.baidu.com")
                .autoApprove(true); //登录后绕过批准询问(/oauth/confirm_access)*/
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager) //配置授权管理认证对象
                .userDetailsService(userDetailsService) //配置加载用户信息的服务
                .authorizationCodeServices(authorizationCodeServices) //授权码服务,添加就可以保存到数据库了
                .accessTokenConverter(jwtAccessTokenConverter) //jwt保存的信息
                .tokenServices(tokenService()) //令牌管理服务,调用上面的方法
                .allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.allowFormAuthenticationForClients()
                .passwordEncoder(bCryptPasswordEncoder)
                .tokenKeyAccess("permitAll()")            //oauth/token_key是公开
                .checkTokenAccess("isAuthenticated()");   //oauth/check_token公开
    }

}

 

如果对我的其它文章有更多的兴趣,可以访问我的个人博客:uniqueho.xyz

 

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
OAuth2.0是一种授权框架,用于保护API、Web应用程序和移动应用程序的资源。OAuth2.0定义了四种授权方式:授权码、隐式、密码和客户端凭证。在Java中,我们可以使用Spring Security框架来实现OAuth2.0服务端和客户端的实现。 OAuth2.0服务端实现: 1. 引入Spring Security OAuth2.0依赖 ``` <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency> ``` 2. 配置OAuth2.0认证服务器 在Spring Security配置类中增加如下配置: ``` @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private DataSource dataSource; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } } ``` 其中,@EnableAuthorizationServer注解表示启用OAuth2.0认证服务器,configure(ClientDetailsServiceConfigurer clients)方法用于配置客户端的信息configure(AuthorizationServerEndpointsConfigurer endpoints)方法用于配置认证服务器的端点。 3. 配置Spring Security 在Spring Security配置类中增加如下配置: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } } ``` 其中,@EnableWebSecurity注解表示启用Spring Security,configure(AuthenticationManagerBuilder auth)方法用于配置用户信息,authenticationManagerBean()方法用于获取认证管理器。 OAuth2.0客户端实现: 1. 引入Spring Security OAuth2.0依赖 ``` <dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> <version>2.3.4.RELEASE</version> </dependency> ``` 2. 配置OAuth2.0客户端 在Spring配置文件中增加如下配置: ``` security.oauth2.client.client-id=<client-id> security.oauth2.client.client-secret=<client-secret> security.oauth2.client.access-token-uri=<access-token-uri> security.oauth2.client.user-authorization-uri=<user-authorization-uri> security.oauth2.client.token-name=<token-name> security.oauth2.client.authentication-scheme=<authentication-scheme> security.oauth2.client.client-authentication-scheme=<client-authentication-scheme> ``` 其中,security.oauth2.client.client-id表示客户端ID,security.oauth2.client.client-secret表示客户端秘钥,security.oauth2.client.access-token-uri表示访问令牌的URI,security.oauth2.client.user-authorization-uri表示用户授权的URI,security.oauth2.client.token-name表示令牌的名称,security.oauth2.client.authentication-scheme表示认证方案,security.oauth2.client.client-authentication-scheme表示客户端认证方案。 3. 使用RestTemplate访问受保护的资源 ``` RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Bearer " + accessToken); HttpEntity<String> entity = new HttpEntity<>(headers); ResponseEntity<String> response = restTemplate.exchange( "http://localhost:8080/api/protected", HttpMethod.GET, entity, String.class); String body = response.getBody(); ``` 其中,accessToken为获取到的访问令牌,"http://localhost:8080/api/protected"为受保护的资源的URI。最后,我们可以通过RestTemplate访问受保护的资源。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hurley11

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值