Spring security implements oauth2 0 - separation of authorization service and resource service

Posted by will35010 on Tue, 15 Feb 2022 09:30:13 +0100

How to build OAuth2.0_01_basic edition authorization service by spring security and advanced edition authorization service by spring security are introduced in two articles 0 authorization server and resource server.

This article will continue to optimize, separate the authorization server and resource server, and deploy them on different servers.

Brief description

Spring Security OAuth2.0 can configure the authorization server and resource server in one application or separately.

The authorization server is responsible for user login, authorization, token authentication, etc.

The resource server is responsible for providing protected resources, but needs to go to the authorization server for token verification.

In this section, the following will be introduced:

  • How to configure authorization server and resource server separately and perform their respective duties.
  • Replace curl command with postman as a tool for interface call.
  • Dependency, entity class, tool class, DAO, Service, authorization page, login page and other contents are no different from those in the previous part, so they will not be repeated. Only the contents that need to be modified will be recorded.

Authorization server configuration

Extract the following from the code in the previous part (Spring Security implements OAuth2.0 advanced):

  • Entity class.
  • Login page and authorization page.
  • DAO and Service layer.
  • Mybatis configuration, Security configuration and authorization server configurator configuration.

Part of the code needs to be modified.

Modify the authorization server configurator configuration

Override the configure(AuthorizationServerSecurityConfigurer) method to configure that the client to verify the token needs to have a ROLE_TRUSTED_CLIENT role.

@Configuration
public class Oauth2AuthorizationServerConfiguration extends
        AuthorizationServerConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private DataSource dataSource;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security)
            throws Exception {
        // Configure the role that the client who comes to verify the token needs to have
        security.checkTokenAccess("hasAuthority('ROLE_TRUSTED_CLIENT')");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients)
            throws Exception {
        // unchanged
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception {
        // unchanged
    }
}

Modify startup class

The startup class deletes the @ EnableResourceServer annotation.

@SpringBootApplication
@EnableAuthorizationServer
@MapperScan("org.net5ijy.oauth2.repository")
public class Oauth2AuthorizationServer {
    public static void main(String[] args) {
        // args = new String[] { "--debug" };
        SpringApplication.run(Oauth2AuthorizationServer.class, args);
    }
}

ResourceServer configuration

Extract the following from the code in the previous part (Spring Security implements OAuth2.0 advanced):

  • Response tool class
  • Protected resource controller

Configure Spring Security

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/order/**").authenticated();

        // Disable CSRF
        http.csrf().disable();
    }
}

Configure resourceserverconfigurator

You need to configure a trusted client to the authorization server to verify the token token.

@Configuration
public class Oauth2ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private static final String URL = "http://localhost:7002/oauth/check_token";

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        RemoteTokenServices tokenService = new RemoteTokenServices();
        tokenService.setCheckTokenEndpointUrl(URL);
        tokenService.setClientId("net5ijy");
        tokenService.setClientSecret("12345678");
        resources.tokenServices(tokenService);
    }
}

Modify startup class

The startup class deletes the @ EnableAuthorizationServer annotation.

@SpringBootApplication
@EnableResourceServer
public class Oauth2ResourceServer {
    public static void main(String[] args) {
        SpringApplication.run(Oauth2ResourceServer.class, args);
    }
}

Test authorization code mode

Start the authorization server first, and then the resource server.

Get authorization_code authorization code

Access with browser:

http://localhost:7002/oauth/authorize?response_type=code&client_id=tencent&redirect_uri=http://localhost:8080&scope=all

Address:

http://localhost:7002/oauth/authorize

parameterexplain
response_typecode
client_idFill in according to the actual client ID, and write tencent here
redirect_uriCallback address after code generation, http://localhost:8080
scopeScope of authority

Login, admin002 and 123456

Allow authorization:

See the browser redirected to http://localhost:8080 And carries the code parameter, which is the authorization code generated by the authorization server:

Get token token

Address:

http://localhost:7002/oauth/token

parameterexplain
grant_typeAuthorization code mode, write authorization_code
scopeScope of authority
redirect_uriCallback address, http://localhost:8080 urlencode required
codeThis is the authorization code generated in the previous step

Use postman to get the token token.

Return value:

{
    "access_token": "e50a400c-439f-4df0-95d5-79154d2cbf87",
    "token_type": "bearer",
    "refresh_token": "29ac936f-69ef-4356-91b1-775fbec65805",
    "expires_in": 3599,
    "scope": "all"
}

In this way, the token token is obtained. The access permission range of the token is all permission, which will expire after 1 hour.

Using token to access resources

http://localhost:7003/order/demo?access_token=e50a400c-439f-4df0-95d5-79154d2cbf87

Source download

https://gitee.com/xuguofeng2020/springsecurityoauth2

Topics: Java Spring Spring Security oauth2