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 writeSpring Cloud
a series of related technologies. AndSpring Cloud
rely onSpringboot
,security
orSpring Security
something 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-oauth2
This dependence should already containspring security
relatedjar
, but thespring-cloud-dependencies
versionGreenwich.RELEASE
, thespring-security-oauth2-autoconfigure
sub-module version has been introduced2.1.0.M4
, whether it is local to re-import or deletemaven repository
do not work, the official ofissue
the same problem was also encountered , it is more dependent on the introduction of temporary use alonespring-security-oauth2-autoconfigure
,version
must 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
@EnableAuthorizationServer
annotation tellsSpring
activation authorization server - Meanwhile
@Configuration
annotations implementsAuthorizationServerConfigurer
class interface indicates that this is an authorization server configuration class. - Used herein
AuthorizationServerConfigurerAdapter
is theSpring
default implementation providesAuthorizationServerConfigurer
an interface class, which are empty method - Injection
authenticationManager
, which isSpring
provided by default, if you need to usepassword
mode, 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 tokenStore
Herein used temporarilyInMemoryTokenStore
,Spring
and also provides the following storagetoken
modeClientDetailsServiceConfigurer
It is to configure the client authorization server certificate issuedclient.inMemory()
Client information is stored in the memorywithClient
Andsecret
is a client ofusername
andpassword
scopes
Mandate is, for example, the client can read and writeauthorizedGrantTypes
Authorization is configured, can beOAuth2.0
supported 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 permissionsAuthenticationManagerBuilder
Arranged in a user memory forpassword
pattern acquisitiontoken
BCryptPasswordEncoder
Configure encryption implementation class
Get token
After completion of the above project started, start the project, spring security
will 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 client
of username
and password
the base64
encoding in http header
the
In http body
the input
After sending the request, get the response, which access_token
is what we use in the subsequent request token interface
to sum up
Above is the use of spring security
simple 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!