Spring Boot中的基本Auth + oAuth实现

Dev*_*bby 6 oauth-2.0 spring-boot

我试图在springboot中实现Basic Auth + oAuth2,意味着一些url在登录系统后应该像传统方式一样工作,有些应该在AOuth2上工作.

就像我想允许管理面板访问SuperAdmin一样,url从

/超级管理员/****

我只想在一般登录系统后访问所有这些URL.

和Rest服务应该使用url start表单在AOuth2上工作

/ API/VI/****

这些网址用于访问申请人.

另外两者都工作正常,但两者都不起作用.

这是我的配置.

import in.kpis.tracking.configuration.CustomAuthenticationSuccessHandler;
import in.kpis.tracking.service.AdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

@Configuration
public class OAuth2ServerConfiguration {

    protected static final String RESOURCE_ID = "restservice";

    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(ResourceServerSecurityConfigurer resources) {
            // @formatter:off
            resources.resourceId(RESOURCE_ID);
            // @formatter:on
        }

        @Override
        public void configure(HttpSecurity http) throws Exception {
            http
                    .authorizeRequests()
                    .antMatchers("/api/v1/*").hasRole("ADMIN")
                    .antMatchers("/greeting").authenticated();
        }
    }


    @Configuration
    public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        private AdminUserService adminUserService;

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(adminUserService);
        }

        @Override
        @Bean
        public AuthenticationManager authenticationManagerBean() throws Exception {
            return super.authenticationManagerBean();
        }

    }

    @Configuration
    @Order(1)
    public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {

            String[] permitAll = new String[]{"/error"};
            String[] permitToSuperAdmin = new String[]{
                    "/superAdmin/*",
            };

            http.authorizeRequests()
                    .antMatchers(permitToSuperAdmin).access("hasRole('SUPER_ADMIN')")
                    .antMatchers("/login").permitAll()
                    .and().formLogin().loginPage("/userLogin.html")
                    .usernameParameter("username")
                    .passwordParameter("password")
                    .loginProcessingUrl("/login")
                    .successHandler(new CustomAuthenticationSuccessHandler())
                    .and()
                    .logout().logoutSuccessUrl("/userLogin.html?logout")
                    .deleteCookies("JSESSIONID")
                    .invalidateHttpSession(true);
            http.csrf().disable();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 8

这实际上已经在Multiple HttpSecurity下的Spring security Guide中进行了解释

@Configuration
@Order(1)                                                        2
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http
            .antMatcher("/api/**")                               3
            .authorizeRequests()
                .anyRequest().hasRole("ADMIN")
                .and()
            .httpBasic();
    }
}

@Configuration                                                   4
public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }
}
Run Code Online (Sandbox Code Playgroud)

并且要使用资源服务器保护 OAuth2 端点,您可以按如下方式配置您的资源服务器

@Configuration
@EnableResourceServer
@Order(1)
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {



    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.resourceId("resource-id");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatcher(new OAuthRequestedMatcher())
            .authorizeRequests().anyRequest().fullyAuthenticated();

    }
}

private static class OAuthRequestedMatcher implements RequestMatcher {
    public boolean matches(HttpServletRequest request) {
        String auth = request.getHeader("Authorization");
        boolean haveOauth2Token = (auth != null) && auth.startsWith("Bearer");
        boolean haveAccessToken = request.getParameter("access_token")!=null;
        return haveOauth2Token || haveAccessToken;
    }
}
Run Code Online (Sandbox Code Playgroud)


Ján*_*aša 6

如果您需要为应用程序的不同部分安装不同的安全设置,则需要创建单独的Spring Security @Configuration-s,其中每个安全设备只配置一个身份验证机制.每个配置都应指定它所涵盖的URI以及需要配置的配置@Order.没有@Order注释的配置被认为是最后一个 - 后备.它在Spring Security参考手册中有所描述.

所以你需要三种配置:

  1. 一为http.antMatcher("/superAdmin/**")...@Order(1).
  2. 一为API http.antMatcher("/api/vi/**")...使用@Order(2).
  3. 没有@Order指定注释的后备配置,不对其他资源进行身份验证.

  • 你需要调用`http.antMatcher(...)`.它很容易与`http.authorizeRequests().antMatchers(...)`混淆,但它有所不同. (3认同)
  • 嘿,我不确定它是否可以一起工作,看我又有更新问题了,但是这个配置不起作用,如果我评论 Order 1 配置它将与 oAuth 一起工作,并且登录身份验证不起作用,如果我取消注释 Order 1 配置,然后 oAuth 身份验证将不起作用并且登录开始工作。 (2认同)

Kra*_*ken -6

很好的问题为了将 oAuth 与 Spring Security 一起使用,我认为没有任何方法可以使用它。您需要创建两个不同的项目,一个用于一般用途。一个用于 oAuth。