Spring Cloud Security OAuth2.0 entry: AuthorizationServer build (a)

Recently and using a variety of learning in the framework of the micro-service-related knowledge, in the process built in, we encountered many problems, but are not recorded, resulting in over a period of time, there was no impression .. so I decided to dig in gold writing. First, in order to record their knowledge in writing the code in the process as well as problem-solving, for easy access; the second is to be able to discuss with other friends, we can absorb different ideas and different options, extension ideas.

The reason for the title Spring Cloud Security, is because you want to write Spring Clouda series of related technologies. And Spring Cloudrely on Springboot, securityor Spring Securitysomething of the module, not much different in nature.

In the process of writing, they encounter unfamiliar or did not grasp the concept and knowledge will be cautious confirmation. We will try to ensure that any code released is operational. However, due to their limited technical capacity, it is inevitable there will be mistakes, including but not limited to 拼写错误, 代码错误, 有代码洁癖的人看着缩进不舒服, 概念理解有偏差, 代码不够优雅and so on, I hope you can feel free, do not like do not spray ~

Knowledge base

Ruan Yifeng introduced teacher OAuth2.0

New microservice, as for all services parent, while introducing dependence

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
    <spring.cloud.dependencies.version>Greenwich.RELEASE</spring.cloud.dependencies.version>
    <spring-security-oauth2-autoconfigure.version>2.1.5.RELEASE</spring-security-oauth2-autoconfigure.version>
</properties>
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.dependencies.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.security.oauth.boot</groupId>
                <artifactId>spring-security-oauth2-autoconfigure</artifactId>
                <version>${spring-security-oauth2-autoconfigure.version}</version>
            </dependency>
        </dependencies>
</dependencyManagement>
复制代码

New uaa-service, as authentication and authorization services, introduction of dependence

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-oauth2</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.security.oauth.boot</groupId>
                <artifactId>spring-security-oauth2-autoconfigure</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework.security.oauth.boot</groupId>
        <artifactId>spring-security-oauth2-autoconfigure</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
</dependencies>
复制代码

spring-cloud-starter-oauth2This dependence should already contain spring securityrelated jar, but the spring-cloud-dependenciesversion Greenwich.RELEASE, the spring-security-oauth2-autoconfiguresub-module version has been introduced 2.1.0.M4, whether it is local to re-import or delete maven repositorydo not work, the official of issuethe same problem was also encountered , it is more dependent on the introduction of temporary use alone spring-security-oauth2-autoconfigure, versionmust also be specified in the sub-module, I do not know whether you have encountered this problem.

Authorization Server Configuration

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

	@Autowired
	private AuthenticationManager authenticationManager;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Override
	public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
		super.configure(security);
	}

	@Override
	public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
		clients.inMemory()
				.withClient("client-id")
				.secret(passwordEncoder.encode("client-secret"))
				.scopes("read", "write")
				.authorizedGrantTypes("password", "refresh_token")
				.authorities("user:view");
	}

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

	@Bean
	public TokenStore tokenStore() {
		return new InMemoryTokenStore();
	}
}
复制代码
  • Use @EnableAuthorizationServerannotation tells Springactivation authorization server
  • Meanwhile @Configurationannotations implements AuthorizationServerConfigurerclass interface indicates that this is an authorization server configuration class.
  • Used herein AuthorizationServerConfigurerAdapteris the Springdefault implementation provides AuthorizationServerConfigureran interface class, which are empty method
  • Injection authenticationManager, which is Springprovided by default, if you need to use passwordmode, you must explicitly configureendpoints.authenticationManager(authenticationManager)
  • General projects like password fields will not use plaintext encryption, so here is injected passwordEncoder, is used to encrypt the user password verification, and when you create a user password
  • tokenStoreHerein used temporarily InMemoryTokenStore, Springand also provides the following storage tokenmode
  • ClientDetailsServiceConfigurerIt is to configure the client authorization server certificate issued
    • client.inMemory()Client information is stored in the memory
    • withClientAnd secretis a client of usernameandpassword
    • scopesMandate is, for example, the client can read and write
    • authorizedGrantTypesAuthorization is configured, can be OAuth2.0supported in a way, it can be customized

Configuring User

@Configuration
@EnableGlobalMethodSecurity(proxyTargetClass = true, prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth
		    .inMemoryAuthentication()
		    .withUser("admin")
		    .password(passwordEncoder().encode("password"))
		    .roles("ADMIN");
	}

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

	@Bean
	@Override
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}
}
复制代码
  • @EnableGlobalMethodSecurity(proxyTargetClass = true, prePostEnabled = true)Open method validation level permissions
  • AuthenticationManagerBuilderArranged in a user memory for passwordpattern acquisitiontoken
  • BCryptPasswordEncoderConfigure encryption implementation class

Get token

After completion of the above project started, start the project, spring securitywill provide us with a few endpoint, one of which is to obtain a token: /oauth/token. Http requests using toolspostman

As shown above, after the input, the previous configuration will clientof usernameand passwordthe base64encoding in http headerthe

In http bodythe input

After sending the request, get the response, which access_tokenis what we use in the subsequent request token interface

to sum up

Above is the use of spring securitysimple structures authorization server, you can see still pretty convenient. But if it is used in a production environment, far from enough, for example, user information, client information, token persistent information, a variety of exception handling, resource allocation server, etc., follow-up article will continue to improve in, thanks!

Guess you like

Origin blog.csdn.net/weixin_33984032/article/details/91370183