繁体   English   中英

如何在Spring Boot Security OAuth2应用程序中仅对某些类启用OAuth2?

[英]How do I enable OAuth2 for only certain classes in my Spring Boot Security OAuth2 app?

我按照本指南添加了OAuth2

https://spring.io/guides/tutorials/bookmarks/#_securing_a_rest_service

但是现在,它需要对每个页面进行身份验证!

$ curl -s http://localhost:8080/login 
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

我只想在一个特定的类中对API使用OAuth2。 我尝试阅读Spring Boot的参考

https://docs.spring.io/spring-boot/docs/1.5.14.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-security

但这根本没有帮助! 它给出了0个例子。

要自定义它,通常使用外部属性和WebSecurityConfigurerAdapter类型的bean(例如,添加基于表单的登录名)。
可以使用外部属性(安全性*)打开或关闭以上所有内容或对其进行修改。 要覆盖访问规则而不更改任何其他自动配置的功能,请添加具有@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)类型的WebSecurityConfigurerAdapter类型的@Bean并对其进行配置以满足您的需求。

如何自定义它? 哪些属性? 如何配置以满足您的需求?

我尝试设置application.properties

security.basic.enabled = false
security.ignored = /login

但是它仍然需要OAuth2身份验证。 我只想为类IShortUrlApiInteface启用OAuth2,并为所有其他@Controllers禁用它。

创建一个类,扩展ResourceServerConfigurerAdapter ,并重写configure(HttpSecurity)方法。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    String [] ignoredPaths = new String[]{
            "/robots.txt", "/error", "/login", "/doLogut", "/home", "/pageNotFound", 
            "/css/**", "/js/**", "/fonts/**", "/img/**", ...
    };

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

        http.authorizeRequests()
            .antMatchers(ignoredPaths).permitAll()
            .anyRequest().authenticated()
        .and()
            .httpBasic();   
    }

对于您的情况,您需要设置登录URI的权限。 如果您使用微服务架构,则需要在每个项目/服务中创建资源配置。

  • security.oauth2.resource.user-info-uri定义授权服务URI
  • clientId定义您的实际客户ID
  • 在oauth中,需要为每个资源服务器创建唯一的resource-id。下面是资源服务器的示例。

    @Configuration @EnableResourceServer
    公共类ResourceConfig扩展了ResourceServerConfigurerAdapter {@Value(“ $ {security.oauth2.resource.user-info-uri}”)私有字符串userInfoUri;

     @Value("${client-id}") private String clientId; @Override public void configure(final ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId("ig-user"); } @Override public void configure(final HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/api/v1/user/activate/**").permitAll()// .antMatchers("/api/v1/user/access/check/**").permitAll()// .antMatchers("/api/v1/profile/exists/**").permitAll()// .antMatchers("/api/v1/user/sign-up/**").permitAll()// .antMatchers("/download/**").permitAll()// .anyRequest().authenticated(); } @Primary @Bean public UserInfoTokenServices tokenService() { final UserInfoTokenServices tokenService = new UserInfoTokenServices(userInfoUri, clientId); return tokenService; } 

    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM