SpringBoot2 integrates OAuth2 components to simulate third-party authorized access

Source code of this article: GitHub·click here || GitEE·click here

1. Mode description

Authorization service

Verify the identity of third-party services, verify the identity of mailbox users, record and manage authentication tokens, and provide Token verification for the resource server. Scenario: A third-party website uses the user's mailbox to log in and access the basic information, avatar, name, etc. of the mailbox account.

Resource Service

Some information that a third-party service needs to obtain after logging in through an email account is understood as a resource and stores the data resource of the email account.

Third party service

That is, with the help of the account of the mailbox user, quickly log in to the third service, eliminating the complicated registration process and helping to quickly accumulate new users.

Interactive process

The third-party service opens the fast mailbox login function to users, guides users to the mailbox authentication service, and returns the identity token to the third-party service after authentication. The third-party service carries the token to access the resource service of the mailbox and obtains some basic mailbox user information .

Two, project configuration management

1. Case structure

Core dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security.oauth</groupId>
    <artifactId>spring-security-oauth2</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

There are two core component dependencies: OAuth2 component and Security component.

Module division

  • auth-server: authorization service
  • resource-server: resource server
  • third-server: the third service

2. Configuration description

【Authorization Service】

OAuth2 configuration

The configuration management here is the authorization process of the third party and the identity certificate ClientID and password issued to the third party. The actual scenario is that the third party logs in with an email account. The first thing is to provide materials to the email manager to obtain the identity certificate for accessing the email service. , And then can dock open services, this model is very common in third-party docking business.

/**
 * 模拟第三方授权配置
 */
@EnableAuthorizationServer
@Configuration
public class AuthConfig extends AuthorizationServerConfigurerAdapter {
    
    

    @Resource
    ClientDetailsService clientDetailsService;

    /**
     * 资源服务器校验Token
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
    
    
        security.checkTokenAccess("permitAll()").allowFormAuthenticationForClients();
    }
    /**
     * 第三方客户端请求配置,和资源服务访问的配置,不设置默认都可以访问,提供默认回调地址
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    
    
        clients.inMemory()
                .withClient("third01")
                .secret(new BCryptPasswordEncoder().encode("third01"))
                .resourceIds("resource-01")
                .authorizedGrantTypes("authorization_code","refresh_token")
                .scopes("all")
                .redirectUris("http://localhost:8082/notify.html");
    }
    /**
     * 配置访问端点
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
    
    
        endpoints.authorizationCodeServices(authorizationCodeServices()).tokenServices(tokenServices());
    }
    /**
     * 内存管理
     */
    @Bean
    AuthorizationCodeServices authorizationCodeServices() {
    
    
        return new InMemoryAuthorizationCodeServices();
    }
    /**
     * Token管理规则
     */
    @Bean
    AuthorizationServerTokenServices tokenServices() {
    
    
        DefaultTokenServices services = new DefaultTokenServices();
        services.setClientDetailsService(clientDetailsService);
        services.setSupportRefreshToken(true);
        services.setTokenStore(tokenStore());
        services.setAccessTokenValiditySeconds(3600);
        services.setRefreshTokenValiditySeconds(3600*7);
        return services;
    }
    @Bean
    TokenStore tokenStore() {
    
    
        return new InMemoryTokenStore();
    }
}

Usually need to store third-party information in the database, you can go to the OAuth2 open source project, get the table structure and put it in the local database, and then change to the data source loading mode here. Simple process management is written in the source code with SQL statements, data The source can be introduced.

Security configuration

/**
 * 模拟本地用户配置
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    
    /**
     * 密码加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
    
    
        return new BCryptPasswordEncoder();
    }
    /**
     * 内存中虚拟用户和角色
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(new BCryptPasswordEncoder().encode("123456"))
                .roles("user");
    }
    /**
     * 表单登录
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
    
        http.csrf().disable().formLogin();
    }
}

Based on the configuration here to manage the authentication process of email users, such as using email account password login verification to determine whether the authorization is established, here is the service local email account, and the data stored based on the data source is available in the following cases.

About several components related to security authentication in the Spring framework, you can learn about it before using OAuth2.

【Resource Service】

There are three main functions. Configure the Token verification mechanism carried by the third party, that is, the access authorization service verification interface, here is the OAuth2 customized interface; configure the resourceId resource service number to control the third service function Access to the resource service range belongs to the control of a large authority point; it simulates and verifies the role of the user, and has a finer control authority.

/**
 * 资源服务管理配置
 */
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
    
    
    /**
     * Token令牌校验
     */
    @Bean
    RemoteTokenServices tokenServices() {
    
    
        RemoteTokenServices services = new RemoteTokenServices();
        services.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        services.setClientId("third01");
        services.setClientSecret("third01");
        return services;
    }
    /**
     * 服务资源ID配置
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
    
    
        resources.resourceId("resource-01").tokenServices(tokenServices());
    }
    /**
     * 模拟用户权限规则
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
    
    
        http.authorizeRequests()
                .antMatchers("/user/**").hasRole("user")
                .anyRequest().authenticated();
    }
}

【Third Party Service】

It mainly provides simulation of two processes: request authorization service to obtain identity token; carry identity token to request resource service to obtain data. Here is the processing method of the authorization code callback interface.

@Controller
public class NotifyController {
    
    

    private static final Logger LOG = LoggerFactory.getLogger(NotifyController.class);

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/notify.html")
    public String notify(String code, Model model) {
    
    
        if (code != null) {
    
    
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("code", code);
            map.add("client_id", "third01");
            map.add("client_secret", "third01");
            map.add("redirect_uri", "http://localhost:8082/notify.html");
            map.add("grant_type", "authorization_code");
            Map<String,String> resp = restTemplate.postForObject("http://localhost:8080/oauth/token", map, Map.class);
            String accessToken = resp.get("access_token");
            LOG.info("身份令牌:{}",accessToken);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Authorization", "Bearer " + accessToken);
            HttpEntity<Object> httpEntity = new HttpEntity<>(headers);
            ResponseEntity<String> entity = restTemplate.exchange("http://localhost:8081/user/resource", HttpMethod.GET, httpEntity, String.class);
            model.addAttribute("notifyMsg", entity.getBody());
        }
        return "notify";
    }
}

Three, the test process

Through the above test process, compare the common third-party login mechanism to understand the authorization code mode of OAuth2.

Fourth, the source code address

GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent

Recommended reading: finishing programming system

Serial number project name GitHub address GitEE address Recommended
01 Java describes design patterns, algorithms, and data structures GitHub·click here GitEE·Click here ☆☆☆☆☆
02 Java foundation, concurrency, object-oriented, web development GitHub·click here GitEE·Click here ☆☆☆☆
03 Detailed explanation of SpringCloud microservice basic component case GitHub·click here GitEE·Click here ☆☆☆
04 SpringCloud microservice architecture actual combat comprehensive case GitHub·click here GitEE·Click here ☆☆☆☆☆
05 Getting started with SpringBoot framework basic application to advanced GitHub·click here GitEE·Click here ☆☆☆☆
06 SpringBoot framework integrates and develops common middleware GitHub·click here GitEE·Click here ☆☆☆☆☆
07 Basic case of data management, distribution, architecture design GitHub·click here GitEE·Click here ☆☆☆☆☆
08 Big data series, storage, components, computing and other frameworks GitHub·click here GitEE·Click here ☆☆☆☆☆

Guess you like

Origin blog.csdn.net/cicada_smile/article/details/111503084