Home > AI > Backend > SpringBoot > spring-security-oauth2 >

Get token

Preparation: you need database or WebSecurityConfigurerAdapter will throw an error.

pom.xml

<!--JPA数据库持久化-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

application.properties

# change to none after production
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/test
spring.datasource.username=springuser
spring.datasource.password=ROOTmary88!
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver

Step 1: install dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId></dependency>

<dependency>
        <groupId>org.springframework.security.oauth</groupId>
            <artifactId>spring-security-oauth2</artifactId>
            <version>2.3.4.RELEASE</version>
</dependency>

Step 2: Codes

AuthorizationManagerConfig.java

@Configuration
public class AuthenticationManagerConfig extends GlobalAuthenticationConfigurerAdapter {

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

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user")
                .password(passwordEncoder().encode("pass"))
                .roles("USER");
    }
}

AuthorizationServerConfig.java

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                .withClient("client-id")
                .secret(passwordEncoder.encode("client-secret"))
                .authorizedGrantTypes("password")
                .scopes("resource-server-read", "resource-server-write")
                .accessTokenValiditySeconds(60 * 60 * 5)
                .refreshTokenValiditySeconds(60 * 60 * 24 * 3);
    }
}

WebSecurityConfig.java

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

}

Step 3: test with Postman

POST http://localhost:8082/oauth/token

Authorization -> Basic Authorization

username: client-id
password: client-secret

Params

grant_type: password
username: user
password: pass

you should get this response

{
    "access_token": "c25a7803-406a-4408-ac8f-a3a0c15d4846",
    "token_type": "bearer",
    "expires_in": 17999,
    "scope": "resource-server-read resource-server-write"
}

Now, you have the access token, but still you cannot use token to access the resources, since the token need to be saved.

Leave a Reply