Spring Security Oauth2 ResourceServerConfigurerAdapter (资源服务器配置)

ResourceServerConfigurerAdapter (资源服务器配置)

内部关联了ResourceServerSecurityConfigurer 和 HttpSecurity。前者与资源安全配置相关,后者与http安全配置相关

    /**
     * ResourceServerSecurityConfigurer主要配置以下几方面:
     * tokenServices:ResourceServerTokenServices 类的实例,用来实现令牌访问服务,如果资源服务和授权服务不在一块,就需要通过RemoteTokenServices来访问令牌
     * tokenStore:TokenStore类的实例,定义令牌的访问方式
     * resourceId:这个资源服务的ID
     * 其他的拓展属性例如 tokenExtractor 令牌提取器用来提取请求中的令牌。
     */

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        //resourceId 用于分配给可授予的clientId
        // stateless  标记以指示在这些资源上仅允许基于令牌的身份验证
        // tokenStore token的存储方式(上一章节提到)
        resources.resourceId(RESOURCE_ID).stateless(true).tokenStore(tokenStore)
                //authenticationEntryPoint  认证异常流程处理返回
                // tokenExtractor token获取方式,默认BearerTokenExtractor
                // 从header获取token为空则从request.getParameter("access_token")
                .authenticationEntryPoint(authenticationEntryPoint).tokenExtractor(unicomTokenExtractor);
    }

其他属性:
accessDeniedHandler          权失败且主叫方已要求特定的内容类型响应
resourceTokenServices        加载 OAuth2Authentication 和 OAuth2AccessToken 的接口

eventPublisher                     事件发布-订阅  根据异常的clazz触发不同event

 

    @Configuration
    @EnableResourceServer
    protected class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
    /**
     * HttpSecurity配置这个与Spring Security类似:
     * 请求匹配器,用来设置需要进行保护的资源路径,默认的情况下是保护资源服务的全部路径。
     */

        @Override
        public void configure(HttpSecurity http) throws Exception {

            AuthenticationManager oauthAuthenticationManager = oauthAuthenticationManager(http);
            //OAuth2核心过滤器
            resourcesServerFilter = new OAuth2AuthenticationProcessingFilter();
            resourcesServerFilter.setAuthenticationEntryPoint(authenticationEntryPoint);
            //OAuth2AuthenticationManager,只有被OAuth2AuthenticationProcessingFilter拦截到的oauth2相关请求才被特殊的身份认证器处理。
            resourcesServerFilter.setAuthenticationManager(oauthAuthenticationManager);
            if (eventPublisher != null) {
                //同上
                resourcesServerFilter.setAuthenticationEventPublisher(eventPublisher);
            }
            if (tokenExtractor != null) {
                //同上
                resourcesServerFilter.setTokenExtractor(tokenExtractor);
            }
            resourcesServerFilter = postProcess(resourcesServerFilter);
            resourcesServerFilter.setStateless(stateless);

            if (!Boolean.TRUE.toString().equals(apolloCouponConfig.getOauthEnable())) {
                // 不需要令牌,直接访问资源
                http.authorizeRequests().anyRequest().permitAll();
            } else {
                http
                        //.anonymous().disable()  //匿名访问
                        .antMatcher("/**")        //匹配需要资源认证路径
                        .authorizeRequests()
                        .antMatchers("/swagger-ui.html", "/swagger-resources/**",
                                "/v2/api-docs/**", "/validatorUrl","/valid"
                        ).permitAll()            //匹配不需要资源认证路径
                        .anyRequest().authenticated()
                        .and()
                        .addFilterBefore(resourcesServerFilter, AbstractPreAuthenticatedProcessingFilter.class)
                        .exceptionHandling() //添加filter
                        .exceptionHandling().accessDeniedHandler(accessDeniedHandler)  //异常处理
                        .authenticationEntryPoint(authenticationEntryPoint);   //认证异常流程 
            }
        }
    }

accessDeniedHandler  异常 :  令牌不能访问该资源 (403)异常等   

authenticationEntryPoint  异常 : 不传令牌,令牌错误(失效)等

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot 中的 OAuth 资源服务器配置需要在应用程序的配置文件中添加一些属性,并在应用程序中启用 OAuth 资源服务器。 1. 在配置文件中添加以下属性: - spring.security.oauth2.resource.jwt.key-value: 用于验证 JWT 令牌的公钥或私钥 - spring.security.oauth2.resource.user-info-uri: 用于获取用户信息的 URI 2. 在应用程序中启用 OAuth 资源服务器: - 在主类中添加 @EnableResourceServer 注解 - 在配置类中添加 @EnableAuthorizationServer 注解 3. 配置安全配置类,在这个类中添加配置信息 参考代码: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Value("${spring.security.oauth2.resource.jwt.key-value}") private String jwtKeyValue; @Value("${spring.security.oauth2.resource.user-info-uri}") private String userInfoUri; @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("resource-server-rest-api").tokenStore(tokenStore()); } @Bean public TokenStore tokenStore() { return new JwtTokenStore(jwtTokenEnhancer()); } @Bean protected JwtAccessTokenConverter jwtTokenEnhancer() { JwtAccessTokenConverter converter = new JwtAccessTokenConverter(); converter.setSigningKey(jwtKeyValue); return converter; } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .and() .requestMatcher(new OAuthRequestedMatcher()); } private static class OAuthRequestedMatcher implements RequestMatcher { public boolean matches(HttpServletRequest request) { String auth = request.getHeader("Authorization"); // Determine if the client request contained an OAuth Authorization boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer"); boolean haveAccessToken = request.getParameter(" ### 回答2: Spring Boot中的OAuth资源服务器配置是通过添加相关依赖和配置文件来实现的。 首先,我们需要在项目的pom.xml文件中添加Spring SecuritySpring Security OAuth2的依赖,例如: ``` <dependencies> <!-- Spring Security --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <!-- Spring Security OAuth2 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> </dependencies> ``` 然后,我们需要在项目的配置文件(例如application.yml)中配置相关的OAuth2资源服务器属性,例如: ``` spring: security: oauth2: resourceserver: jwt: issuer-uri: <身份验证服务器的URL> ``` 在上述配置中,我们需要指定身份验证服务器的URL,它将用于验证和解析传入的JWT令牌。 接下来,我们可以创建一个类来配置资源服务器的行为,例如: ```java @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/public/**").permitAll() .anyRequest().authenticated(); } } ``` 在上述示例中,我们使用@EnableResourceServer注解启用资源服务器,并指定了访问权限规则。在这个例子中,我们允许/public路径下的请求被所有人访问,其他任何请求都需要通过身份验证。 最后,我们可以使用@RestController注解创建一个简单的REST控制器来演示资源服务器的功能,例如: ```java @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } } ``` 这样,我们就可以使用OAuth2的令牌来访问该控制器所暴露的资源。 综上所述,通过添加依赖、配置属性和编写相关配置类,我们可以在Spring Boot中配置OAuth资源服务器。 ### 回答3: 在Spring Boot中配置OAuth资源服务器包括以下步骤: 1. 添加必要的依赖:在pom.xml文件中添加Spring Security OAuth2依赖。例如,可以添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.security.oauth.boot</groupId> <artifactId>spring-security-oauth2-autoconfigure</artifactId> </dependency> ``` 2. 创建一个配置类:创建一个@Configuration注解的配置类,并使用@EnableResourceServer注解启用资源服务器。例如: ``` @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/api/**").authenticated() .anyRequest().permitAll(); } @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("my-resource-id"); } } ``` 3. 配置访问权限:使用HttpSecurity配置http的请求权限。在上述示例中,`/api/**`路径的请求需要进行身份验证。可以根据实际情况配置其他路径和权限。 4. 配置资源ID:使用ResourceServerSecurityConfigurer配置资源服务器资源ID。资源ID可以是任何唯一标识符,用于标识受保护的资源。 以上是基本的OAuth资源服务器配置步骤。配置完成后,可以使用OAuth2的授权服务器进行认证,并使用访问令牌对受保护的资源进行访问控制。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值