簡體   English   中英

Spring Security Oauth2僅顯示非API請求的登錄頁面

[英]Spring Security Oauth2 only show a login page for non-api requests

我正在使用Spring Boot 1.5.6和OAuth2和JWT的安全性

~/repos/jtor > mvn dependency:tree | grep security
[INFO] +- org.springframework.security.oauth:spring-security-oauth2:jar:2.0.14.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-core:jar:4.2.3.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-config:jar:4.2.3.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-web:jar:4.2.3.RELEASE:compile
[INFO] +- org.springframework.security:spring-security-jwt:jar:1.0.8.RELEASE:compile
[INFO] \- org.springframework.security:spring-security-test:jar:4.2.3.RELEASE:test

通過以下配置,對//api/person請求都將產生標准的OAuth 401:

{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}

我想要的是請求/api/**以獲得401,而將其他任何請求(如//welcome )重定向(302)到我的授權服務器(Ping Federate)。 登錄后,我將被重定向回,我的GET到/將返回我的HTML(或其他內容)。

換句話說,對API的調用將需要令牌,而對非API的調用將遵循oauth2代碼流。

我的配置:

security:
  basic:
    enabled: false
  oauth2:
    client:
      accessTokenUri: https://ping-dev.my-comp.com:9031/as/token.oauth2
      userAuthorizationUri: https://ping-dev.my-comp.com:9031/as/authorization.oauth2
      logoutUri: https://ping-dev.my-comp.com:9031/ext/logout
      clientId: oauth2
      clientSecret: foo
      authentication-scheme: header
    resource:
      jwt:
        keyValue: |
          -----BEGIN PUBLIC KEY-----
          MY KEY HERE
          -----END PUBLIC KEY-----

我的應用程序

@SpringBootApplication
@Slf4j
public class JtorApplication {

    public static void main(String[] args) {
        SpringApplication.run(JtorApplication.class, args);
    }

    @Configuration
    @EnableResourceServer
    protected static class ResourceServer extends ResourceServerConfigurerAdapter {

        @Override
        public void configure(HttpSecurity http) throws Exception {
            // @formatter:off
           http
                   .authorizeRequests()
                   .antMatchers("/info", "/health", "/public/**").permitAll()
                   .anyRequest().fullyAuthenticated();
           // @formatter:on
        }
    }

    /*
     this class allows me to access public resources with a URL that starts with "public/", which
     allows me to bypass security on any public resource in a clean way.
     */
    @Configuration
    protected static class WebMvcConfigurer extends WebMvcConfigurerAdapter {
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/");
        }
    }

    /*
    This is the API I want protected via Oauth2/JWT.
    Only calls containing a valid Bearer token should be allowed.
    Calls without a token should get back a standard Oauth 401 error
     */
    @RestController
    @RequestMapping("/api")
    protected static class ApiController {

        @GetMapping("/person")
        public Person getPerson() {
            return Person.builder().id(1).name("Jason").build();
        }

        @Getter
        @Builder
        static class Person {
            private int id;
            private String name;
        }
    }

    /*
    This is the "web app" controller that returns an "app", which will make ajax calls to the api.
    I want this route to be secured, but instead of just returning a 401, I want to start the
    OAuth login process by sending the user to my OAuth Server
     */
    @Controller
    protected static class WebAppController {

        @RequestMapping("/")
        public String webapp() {
            return "index";
        }

        // this should bypass security because it starts with "public"
        @RequestMapping("/public")
        public String publicPage() {
            return "public";
        }

    }

}

如果要使用不同的身份驗證機制處理應用程序的不同部分,則只需創建擴展WebSecurityConfigurerAdapter其他配置類並在其中指定安全約束即可。

在調用.authorizeRequests .authorizeRequests()之前,請確保在AntMatcher中指定應將安全配置應用到的URL。 請參見下面的代碼。

您可以使用@Order批注設置安全配置的順序。

HTTP基本身份驗證示例

@Configuration
@Order(2) //will be applied after @Order(1), etc...
protected AnotherSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
       http
            .antMatcher("/api/**") //apply only to api endpoints
            .authorizeRequests()
            .antMatchers("/api/admin/**").hasRole("ADMIN")
            .and()
            .httpBasic(); //set to basic auth
    }
}

嘗試這個:

    protected void configure(HttpSecurity http) throws Exception {
        http
....
        .and()
            .exceptionHandling().authenticationEntryPoint(entryPoint())
....
    }

    private AuthenticationEntryPoint entryPoint() {
        return new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                //your code here - can key off of the request
            }
        };
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM