Spring Boot 和 Spring Cloud Security OAUTH 2 SSO 在最新版本中失败

标签 spring spring-boot spring-security oauth-2.0 single-sign-on

我正在尝试使用 OAuth 将示例 Spring Boot 和 Spring Cloud Security 从 Spring Boot 1.4.1 + Brixton.RELEASE 升级到 Spring Boot 1.5.3+ Dalston.RELEASE。然而,经过长时间的艰苦尝试,却没有任何成功。

由于某种原因,资源服务器安全过滤器链似乎没有被触发。因此,对“/me”或“/user”的调用由默认安全过滤器链处理。我在想这是否是秩序的问题。但尝试显式设置安全过滤器链的顺序,如下所示

  • 身份验证服务器 6
  • 网络默认值 5
  • 资源服务器 3(硬编码??)

由于默认过滤器链正在处理请求,因此它始终会转到登录页面,该页面会生成 HTML,并且 SSO 客户端(服务器端 thymeleaf Web UI)会失败。

源码如下

授权服务器

@SpringBootApplication
public class MyAuthServerApplication {

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

然后是授权服务器配置

@Configuration
@EnableAuthorizationServer
@Order(6)
public class AuthorizationServerConfigurer extends A 
uthorizationServerConfigurerAdapter {


@Override
public void configure(ClientDetailsServiceConfigurer clients) throws 
Exception {
    clients.inMemory()
            .withClient("myauthserver")
            .secret("verysecretpassword")
            .redirectUris("http://localhost:8080/")
            .authorizedGrantTypes("authorization_code", "refresh_token")
            .scopes("myscope")
            .autoApprove(true);
}
}

然后是资源服务器类

@Configuration
@EnableResourceServer
public class ResourceServerConfigurer extends 
ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
    http.antMatcher("/user")
            .authorizeRequests()
            .anyRequest()
            .authenticated();
}
}

Web MVC 配置

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

 @Override
 public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("login").setViewName("login");
 }
 }

默认的 Spring Security 配置

@Configuration
@EnableWebSecurity
@Order(9)
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and().csrf()
            .and().formLogin().loginPage("/login");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
{
    auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
}
}

资源 Controller

@RestController
public class ResourceController {

@RequestMapping(value = { "/user" }, produces = "application/json")
public Map<String, Object> user(OAuth2Authentication user) {
    Map<String, Object> userDetails = new HashMap<>();
    userDetails.put("user", user.getUserAuthentication().getPrincipal());
    userDetails.put("authorities",

AuthorityUtils.
 authorityListToSet(user.getUserAuthentication().getAuthorities()));
    return userDetails;
}

}

最后是身份验证服务器的配置 - application.yml

server:
  port: 9090
  contextPath: /auth

logging:
  level:
      org.springframework: INFO
      org.springframework.security: DEBUG

此处未显示 login.html Thymeleaf 模板。

OAUTH 2 SSO 客户端 Web 应用

@SpringBootApplication
public class MyWebsiteApplication {

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

网络安全配置

@Configuration
@EnableOAuth2Sso
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/").permitAll()   // Allow navigating to index 
 page,
            .anyRequest().authenticated();  // but secure all the other URLs
}
}

网络 Controller

@ Controller 公共(public)类 MyWebsiteController {

/**
 * Default index page to verify that our application works.
 */
@RequestMapping("/")
@ResponseBody
public String helloWorld() {
    return "Hello world!";
}

/**
 * Return a ModelAndView which will cause the 
'src/main/resources/templates/time.html' template to be rendered,
 * with the current time.
 */
@RequestMapping("/time")
public ModelAndView time() {
    ModelAndView mav = new ModelAndView("time");
    mav.addObject("currentTime", getCurrentTime());
    return mav;
}

private String getCurrentTime() {
    return LocalTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME);
}
}

应用程序配置 - 客户端 Web 应用程序的 application.yml

server:
  port: 8080
  contextPath: /

security:
  oauth2:
  client:
    accessTokenUri: http://localhost:9090/auth/oauth/token
    userAuthorizationUri: http://localhost:9090/auth/oauth/authorize
    clientId: myauthserver
    clientSecret: verysecretpassword
  resource:
    userInfoUri: http://localhost:9090/auth/user

此处未显示 time.html 页面的 Thymeleaf 模板。

一定有一些微妙的小配置错误或一些我不知道的错误。非常感谢任何帮助或想法。

最佳答案

解决方案

猜测是正确的,安全过滤器链的顺序已更改。这是
的链接 Spring 1.5.x release note

修改后的代码在这里,稍后会上传到Github。身份验证服务器配置上的所有更改。

Spring 安全配置 - 删除 @Order 注解。

@Configuration
@EnableWebSecurity
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {


@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().authenticated()
            .and().csrf()
            .and().formLogin().loginPage("/login");
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception 
{
    auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER")
            .and()
                .withUser("admin").password("admin").roles("USER", "ADMIN");
}
}

然后更改application.yml如下

server:
  port: 9090
  contextPath: /auth

logging:
  level:
    org.springframework: INFO
    org.springframework.security: DEBUG

security:
  oauth2:
    resource:
    filter-order : 3

这样,在身份验证服务器上进行身份验证后,时间就会显示在客户端应用程序/时间 url 上。

关于Spring Boot 和 Spring Cloud Security OAUTH 2 SSO 在最新版本中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44148287/

相关文章:

java - 手动设置经过身份验证的 Spring 用户

java - 我可以将 3 种不同的身份验证方案放在同一个 spring 安全配置中吗?

Spring Boot 使用带有 JSP 模板的资源模板文件夹而不是 webapp 文件夹?

java - Spring Boot 2 拦截器对每个请求解析 `/login'

hibernate - Spring + Hibernate +JTA - HibernateTransactionManager 或 JTATransactionManager

Azure AD 无法与 spring-boot webflux 配合使用

java - 带有 arraylist 拆分和默认空列表的 Spring @Value

java - Spring @async 复制 session

java - Spring 的不同范围

java - Java Spring 中是否可以进行条件聚合?