Basic introduction to OAuth2: Click here for Spring Security 5.0 to make changes to the password. See here for details

Implement a basic OAuth2 authentication

The project uses three independent projects to implement authentication service, resource server and single sign-on server source address respectively

Adding project dependencies

allprojects {
    apply plugin: 'idea'
    apply plugin: 'java'
}
buildscript {
    ext {
        springBootVersion = '. 2.0.0 RELEASE '
    }
    repositories {
        maven { url 'http://maven.aliyun.com/mvn/repository/' }
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")}}subprojects {
    apply plugin: 'java'
    apply plugin: 'org.springframework.boot'
    apply plugin: 'io.spring.dependency-management'
    repositories {
        maven { url 'http://maven.aliyun.com/mvn/repository/' }
        mavenCentral()
    }
}
project("sso-auth-server") {
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web'
        compile 'org.springframework.boot:spring-boot-starter-security'
        compile 'org. Springframework. Security. Request. The boot: spring ws-security - oauth2 - autoconfigure: 2.0.0. RELEASE'}}project("sso-auth-client") {
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web'
        compile 'org.springframework.boot:spring-boot-starter-security'
        compile 'org. Springframework. Security. Request. The boot: spring ws-security - oauth2 - autoconfigure: 2.0.0. RELEASE'}}project("sso-auth-resource") {
    dependencies {
        compile 'org.springframework.boot:spring-boot-starter-web'
        compile 'org.springframework.boot:spring-boot-starter-security'
        compile 'org. Springframework. Security. Request. The boot: spring ws-security - oauth2 - autoconfigure: 2.0.0. RELEASE'}}Copy the code

Authentication Server Configuration

  • Open authentication service using EnableAuthorizationServer annotations
@SpringBootApplication
@EnableAuthorizationServer
public class AuthenticationApplication {

    public static void main(String[] args) {
        newSpringApplicationBuilder(AuthenticationApplication.class) .run(args); }}Copy the code
  • Use the EnableWebSecurity annotation to enable and configure permission authentication
@EnableWebSecurity
public class Oauth2SecurityConfig extends WebSecurityConfigurerAdapter {
    / / configure the bean will be used when doing the AuthorizationServerConfigurer configuration
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean(a) throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                .password(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("admin"))
                .roles("test"); }}Copy the code
  • Oauth2 related configurations
@Configuration
public class Oauth2Config extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        /* Configure the policy for token acquisition and verification */
        security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // Configure oauth2 client information
        // There are 4 authorizedGrantTypes, only 2 are enabled here
        // secret Password configuration Starting from Spring Security 5.0, you must fill in {bcrypt}+ encrypted password format
        clients.inMemory()
                .withClient("testclient")
                .secret(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode("testclient"))
                .scopes("test").authorizedGrantTypes("authorization_code"."refresh_token");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        / / configuration tokenStore
        endpoints.authenticationManager(authenticationManager).tokenStore(memoryTokenStore());
    }
    // Generate tokens using the most basic InMemoryTokenStore
    @Bean
    public TokenStore memoryTokenStore(a) {
        return newInMemoryTokenStore(); }}Copy the code

Resource Server Configuration

  • Use the EnableResourceServer annotation to start the resource service
@SpringBootApplication
@EnableResourceServer
@RestController
public class ResourceApplication {
    private static final Logger log = LoggerFactory.getLogger(ResourceApplication.class);

    public static void main(String[] args) {
        new SpringApplicationBuilder(ResourceApplication.class)
                .run(args);
    }
    // Add a test access interface
    @GetMapping("/user")
    public Authentication getUser(Authentication authentication) {
        log.info("resource: user {}", authentication);
        returnauthentication; }}Copy the code
  • Configure oAuth2 client information
auth-server: http://localhost:8080 Address of the authentication server

server:
  port: 8086
security:
  oauth2:
    client:
      client-id: testclient The client ID of the authorization server configuration
      client-secret: testclient Client secret for authorization server configuration
      scope: test
      access-token-uri: ${auth-server}/oauth/token # Access token interface
      user-authorization-uri: ${auth-server}/oauth/authorize Obtain the Authorization Code interface
    resource:
      token-info-uri: ${auth-server}/oauth/check_token Verify the token interface
# user-info-uri: ${auth-server}/user # a custom interface to obtain authentication and authorization, either on the authorization server or on other servers
# prefer-token-info: true # if both token-info-uri and user-info-uri are configured, this phenomenon sets which authentication authorization is used

Copy the code

Configure a single sign-on server

  • Configure the SSO service using the EnableOAuth2Sso annotation
@EnableOAuth2Sso
@SpringBootApplication
@RestController
public class SsoApplication {
    private static final Logger log = LoggerFactory.getLogger(SsoApplication.class);

    public static void main(String[] args) {
        new SpringApplicationBuilder(SsoApplication.class)
                .run(args);
    }
    // SSO test interface
    @GetMapping("/user")
    public Authentication getUser(Authentication authentication) {
        log.info("auth : {}", authentication);
        returnauthentication; }}Copy the code
  • Configure oAuth2 client information
auth-server: http://localhost:8080 Address of the authentication server

server:
  port: 8085
security:
  oauth2:
    client:
      client-id: testclient
      client-secret: testclient
      scope: test
      access-token-uri: ${auth-server}/oauth/token
      user-authorization-uri: ${auth-server}/oauth/authorize
    resource:
      token-info-uri: ${auth-server}/oauth/check_token
Copy the code

The details are the same as the resource server


Sso Usage mode

  1. Start the sso – auth – server
  2. Start the sso – auth – client
  3. accesshttp://127.0.0.1:8085/user If the SSO domain name is the same, the browser uses the same cookie and the login page is redirected all the time. Therefore, set the authentication server and SSO client to start in different domain names.

Resource Server usage

  1. Start the sso – auth – server
  2. Start the sso – auth – the resource
  3. Using oAuth2 protocol to obtain tokens on SSO-Auth-server, you can use tools like Postman.
  4. Access token server resources, such as http://localhost:8086/user? access_token=cd96398b-4565-43dc-941f-c71f51010ee5

Go to Authorization -> Type -> OAuth2.0 in Postman

Click Get New Access Token to configure oAUth information

Access resources after obtaining the token