带有Spring Boot的OAuth2 SSO,没有授权屏幕 [英] OAuth2 SSO with Spring Boot without the authorization screen

查看:89
本文介绍了带有Spring Boot的OAuth2 SSO,没有授权屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用Spring Boot 1.5.3,OAuth2和MongoDB编写的资源,授权和_ui应用程序.

I have resource, authorization and _ui applications written using Spring Boot 1.5.3, OAuth2 and MongoDB.

这些资源将通过移动应用程序和几个Web应用程序(一个用于普通用户,另一个用于管理员)进行访问.这些应用程序非常类似于示例 Dave Syer的指南.区别在于用户存储在数据库中,而客户端存储在授权服务器的resources文件夹中的xml文件中.

The resources are going to be accessed from mobile apps as well as a couple of web applications (one for regular users and the other one for admins). The apps are quite similar to the samples from the guides by Dave Syer. What different is that the users are stored in the database and the clients are stored in an xml file located in the resources folder of the authorization server.

我正在努力为Web用户提供登录体验.遵循基于JWT的OAuth应用程序的指南,在登录页面之后,将用户重定向到授权屏幕,这不是所需的行为.即,我不希望我的授权服务器询问用户是否信任我的Web应用程序来访问其资源.相反,我希望用户像预期的那样在登录后立即将用户重定向到ui页面.

I am struggling with the logon experience for the web users. Following the guides for the JWT based OAuth app, after the login page, the user is redirected to the authorization screen, which is not the desired behavior. I.e., I don't want my authorization server to ask if the user trusts my web application to access its resources. Instead, I want users redirected to the ui pages right after login, as one would expect.

我在GitHub上找到了此项目(非常类似于完全按照我的要求运行,但是一旦我通过添加身份验证和授权实现开始自定义它,它就会恢复为使用授权屏幕.显然,我缺少了一些东西,但是我无法弄清楚到底是什么.

I found this project on GitHub (very similar to the apps from the guide) which behaves exactly as I want, but once I start customizing it by adding my authentication and authorization implementation, it reverts back to using the authorization screen. Apparently, I am missing something, but I was not able to figure out what exactly.

authorization/src/main/resourcs/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

authorization/src/main/resourcs/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>

authorization/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);
    }

}

authorization/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);
    }
}

推荐答案

来自

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

自动批准的范围或范围模式(以逗号分隔),或者 只需"true"即可自动批准所有内容.

Scopes or scope patterns that are autoapproved (comma-separated), or just "true" to autoapprove all.

只需将autoapprove="true"属性添加到client-details.xml中的受信任应用中即可.这样,身份验证服务器将不会请求用户确认以访问资源.

Just add the autoapprove="true" attribute to your trusted-app in client-details.xml. That way the authserver will not request user's confirmation to access the resources.

此处是如何实施此操作的示例行为直接在您的Java配置中进行.

Here is an example of how to implement this behaviour directly in your Java configuration.

这篇关于带有Spring Boot的OAuth2 SSO,没有授权屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆