簡體   English   中英

使用 Spring Boot 的 OAuth2 SSO 沒有授權屏幕

[英]OAuth2 SSO with Spring Boot without the authorization screen

我有使用 Spring Boot 1.5.3、OAuth2 和 MongoDB 編寫的資源、授權和 _ui 應用程序。

這些資源將從移動應用程序和幾個 Web 應用程序(一個供普通用戶使用,另一個供管理員使用)訪問。 這些應用程序與 Dave Syer 的指南中的示例非常相似。 不同之處在於,用戶存儲在數據庫中,而客戶端存儲在授權服務器資源文件夾中的 xml 文件中。

我正在為網絡用戶的登錄體驗而苦苦掙扎。 按照基於 JWT 的 OAuth 應用程序的指南,在登錄頁面之后,用戶將被重定向到授權屏幕,這不是所需的行為。 即,我不希望我的授權服務器詢問用戶是否信任我的 Web 應用程序來訪問其資源 相反,我希望用戶在登錄后立即重定向到 ui 頁面,正如人們所期望的那樣。

在 GitHub 上找到了這個項目(與指南中的應用程序非常相似),它的行為完全符合我的要求,但是一旦我開始通過添加我的身份驗證和授權實現對其進行自定義,它就會恢復使用授權屏幕。 顯然,我遺漏了一些東西,但我無法弄清楚到底是什么。

授權/src/main/resources/application.yml

security:
  oauth2:
    client:
      client-id: trusted-app
      client-secret: secret
      scope: read, write
      auto-approve-scopes: .*
  authorization:
      check-token-access: permitAll()
server:
  port: 9999
  context-path: /uaa
mongo:
  db:
    name: myappname

授權/src/main/resources/client-details.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:oauth="http://www.springframework.org/schema/security/oauth2"

   xsi:schemaLocation="http://www.springframework.org/schema/beans
                    http://www.springframework.org/schema/beans/spring-beans.xsd
                    http://www.springframework.org/schema/security/oauth2
                    http://www.springframework.org/schema/security/spring-security-oauth2.xsd">

<oauth:client-details-service id="client-details-service">

    <!-- Web Application clients -->
    <oauth:client
            client-id="trusted-app"
            secret="secret"
            authorized-grant-types="authorization_code, password,refresh_token"
            authorities="ROLE_WEB, ROLE_TRUSTED_CLIENT"
            access-token-validity="${oauth.token.access.expiresInSeconds}"
            refresh-token-validity="${oauth.token.refresh.expiresInSeconds}"/>
    </oauth:client-details-service>
</beans>

授權/src/main/java/AuthorizationApplication.java

@SpringBootApplication
@RestController
public class AuthorizationApplication extends AuthorizationServerConfigurerAdapter {

    @RequestMapping("/user")
    @ResponseBody
    public Principal user(Principal user) {
        return user;
    }

    @Configuration
    static class MvcConfig extends WebMvcConfigurerAdapter {
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("login").setViewName("login");
            registry.addViewController("/").setViewName("index");
        }
    }

    @Configuration
    @Order(-20)
    static class LoginConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .formLogin().loginPage("/login").permitAll()
            .and()
                .requestMatchers()
                .antMatchers("/", "/login", "/oauth/authorize", "/oauth/confirm_access")
            .and()
                .authorizeRequests()
                .anyRequest().authenticated();
        }
    }

    @Configuration
    @EnableAuthorizationServer
    @ImportResource({"classpath*:client-details.xml"})
    protected static class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter {

        @Autowired
        private AuthenticationManager authenticationManager;

        @Resource(name="client-details-service")
        private ClientDetailsService clientDetailsService;

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients.withClientDetails(clientDetailsService);
        }

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
            endpoints
                .authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter());
        }

        @Bean
        public JwtAccessTokenConverter jwtAccessTokenConverter() {
            JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
            return converter;
        }
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new StandardPasswordEncoder();
    }

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

}

授權/src/main/java/mypackage/UserService.java

@Service
public class UserService implements UserDetailsService {

    private UserAccountRepository userAccountRepository;

    @Autowired
    public UserService(UserAccountRepository userAccountRepository){
        this.userAccountRepository = userAccountRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        UserAccount userAccount = userAccountRepository.findByEmail(s);

        if (userAccount != null) {
            return userAccount;
        } else {
            throw new UsernameNotFoundException("could not find the user '" + s + "'");
        }
   }
}

ui/src/main/resources/application.yml

auth-server: http://localhost:9999/uaa
server:
  port: 8080
spring:
  aop:
    proxy-target-class: true
security:
  oauth2:
    client:
      clientId: trusted-app
      clientSecret: secret
      access-token-uri: ${auth-server}/oauth/token
      user-authorization-uri: ${auth-server}/oauth/authorize
      scope: read, write
    resource:
      token-info-uri: ${auth-server}/oauth/check_token

ui/src/main/java/UiApplication.java

@SpringBootApplication
@EnableOAuth2Sso
public class UiApplication extends WebSecurityConfigurerAdapter{

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

    @Bean
    OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
        return new OAuth2RestTemplate(details, oauth2ClientContext);
    }
}

來自http://www.springframework.org/schema/security/spring-security-oauth2.xsd Element client-details-service > complexType client > attribute autoaprove

自動批准的范圍或范圍模式(以逗號分隔),或者只是“真”以自動批准所有。

只需將autoapprove="true"屬性添加到client-details.xml中的 trusted-app。 這樣 authserver 將不會請求用戶確認訪問資源。

下面是一個示例,說明如何在 Java 配置中直接實現此行為。

此外,如果您的客戶端由數據庫提供,實際上是DataSource ,則相關客戶端的AUTOAPPROVE列應在表OAUTH_CLIENT_DETAILS中設置為“true”。

暫無
暫無

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

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