SpringBoot2.1.5 (35) --- Safety

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/zhangbijun1230/article/details/91358545

 

SpringBoot2.1.5 (37) --- Safety

 Safety

If you add Spring Security dependencies, so web applications by default for all HTTP path (also known as the end point, end point, a specific URL API's) using the 'basic' certification. To add methods to the web application level (method-level) protection, you can add @EnableGlobalMethodSecurityand use the settings you want additional information refer to the Spring Security Reference .

The default AuthenticationManageris only one user ( 'user' username and password will be randomly INFO log level when the application starts to print out), as follows:

Using default security password: 78fa095d-3f4c-48b1-ad50-e24c31d5cf35

Note  If you fine-tune the logging configuration, make sure that org.springframework.boot.autoconfigure.securitycategory logging level INFO, otherwise the default password will not be printed.

You can set security.user.passwordto change the default password, these and other useful attributes SecurityProperties (with "security" as the prefix attribute) is outside of the.

The default security configuration through SecurityAutoConfiguration, SpringBootWebSecurityConfiguration(for web security), AuthenticationManagerConfiguration(can be used to configure non-certified web application) managed. You can add a @EnableWebSecurity bean to completely turn off the default configuration of Spring Boot. To customize it, you need to use an external configuration attributes and WebSecurityConfigurerAdaptertypes of beans (such as, add on the login form). Want to close the configuration management certification, you can add a AuthenticationManagertype of bean, or the @Configurationinjection of a class's method AuthenticationManagerBuilderto configure global AuthenticationManager. Here are some safety-related Spring Boot application examples can be used to reference.

+

The basic characteristics of the web applications you can get out of the box are as follows:

  1. Use a memory storage of AuthenticationManager bean and a user (see the SecurityProperties.Useracquisition of property user).
  2. Ignore (not protected) common static resource path /css/**, /js/**, /images/**( , /webjars/**and  **/favicon.ico).
  3. Implementation of HTTP Basic security protection for all other paths.
  4. Security-related events will be posted to the Spring ApplicationEventPublisher(successes and failures of certification, denied access).
  5. Common underlying characteristics (HSTS, XSS, CSRF, buffer) Spring Security provides default are turned on.

All the above features can be accessed through an external configuration ( security.*) is opened, closed, or modified. Want to overwrite the access rules without changing other properties of automatic configuration, you can add an annotation @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)of WebSecurityConfigurerAdaptertype @Bean.

Note WebSecurityConfigurerAdapter the default will match all paths, if you do not completely cover the access rule Spring Boot automatically configured, you can configure the exact path you want to cover.

MVC security

The default security configuration implementation and user details service is automatically configured in SecurityAutoConfiguration in. Automatic configuration import SpringBootWebSecurityConfiguration security for Web services security and user details Automatically configure authentication, which also

Non-Web applications. To turn off the default Web application security configuration, you can add WebSecurityConfigureAdapter type of bean (This does not disable

For more information about user service configuration or security actuators). To turn off UserDetailsService configuration, you can also add a bean type

UserDetailsService, AuthenticationProvider or AuthenticationManager. There are several security guide Spring application examples to help you get started with common use cases.

You can customize by adding to rewrite WebSecurityConfigureAdapter access rules. SpringBoot provides a convenient method may be used to override actuator endpoints and

Static resources. EndpointRequest can be used to create management.endpoints.web.base-path property. PathRequest be used to create

Request matches the location of the resource is used.

 

SpringMVC and similar applications, you can spring-boot-starter-security- security by adding a dependent. Implements the default security configuration ReactiveSecurityAutoconfiguration and UserDetailsServiceAutoconfiguration in.

ReactiveSecurityAutoConfiguration import of WebFluxSecurityConfiguration Web security and user details Automatically configure authentication service, which is associated with non-Web applications. Close the default Web application security configuration can be added WebFilterChainProxy type of bean (This will not disable the security user details service configuration or actuator). To turn off UserDetailsService configuration, you can also add a bean type

ReactiveUserDetailsService或ReactiveAuthenticationManager。

You can configure access rules by adding custom SecurityWebFilterChain. SpringBoot provide a convenient method for rewriting resource actuators and static endpoint access rules. EndpointRequest be used to create based on management.endpoints.web.base-path attribute.

PathRequest generally be used to create the position of ServerWebExchangeMatcher use of resources.

For example, you can customize the security configuration by adding the following:

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
return http
 .authorizeExchange()
 .matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
 .pathMatchers("/foo", "/bar")
 .authenticated().and()
 .formLogin().and()
 .build();
}

OAuth2

If you add a spring-security-oauth2dependent, you can use the auto-configuration simplifies authentication (Authorization) or server resources (Resource Server) settings, details refer to the Spring Security OAuth 2 Developers Guide .

Authorization server

Want to create an authorization server, and grant access tokens, you need to use @EnableAuthorizationServer, and provide security.oauth2.client.client-idand security.oauth2.client.client-secretconfigure.

Press the above operation, you will be able to create an access token using a client certificate, for example:

$ curl client:secret@localhost:8080/oauth/token -d grant_type=password -d username=user -d password=pwd

/tokenCertification endpoint basic form is client-idand client-secret, usually user user certificate details Spring Security's (Spring Boot default is "user" and a random password).

Want to turn off automatic configuration, configure their own authorization server features, you only need to add a AuthorizationServerConfigurertype @Bean.

Resource server

In order to use the access token, you need a resource server (with the authorization server can be the same). Create a resource server is very simple, just add @EnableResourceServer, to provide some configuration to allow the server to decode the access token. If the application is an authorization server, because it knows how to decode the tokens, so there is no need to do other things. If your app is an independent service, then you need to add one of the following optional configurations:

  • security.oauth2.resource.user-info-uriFor /meresources (e.g., PWS's https://uaa.run.pivotal.io/userinfo).
  • security.oauth2.resource.token-info-uriEndpoint for token decoding (e.g., PWS's https://uaa.run.pivotal.io/check_token).

If user-info-uriand token-info-uriare specified, you can set the flag you want to filter out most of the (default prefer-token-info=true).

In addition, if the token is JWTs, you can configure security.oauth2.resource.jwt.key-valuedecode them (key test is signed key). The test key may be signed a symmetric key may be a PEM-encoded RSA public key. If you do not key, and it is open, you can security.oauth2.resource.jwt.key-uriprovide a download URI (JSON objects have a "value" field), for example, on the PWS Platform:

$ curl https://uaa.run.pivotal.io/token_key
{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBI...\n-----END PUBLIC KEY-----\n"}

Note  If you use security.oauth2.resource.jwt.key-urithe authorization server needs to be up and running when the application starts, if can not find the key, it outputs warning, and tells you how to solve.

User Info in Token Types

Google and other third-party identity (identity) provider, there are strict requirements of the token type name request headers sent to the user info endpoint set. The default Bearerfor most providers require, if necessary you can set security.oauth2.resource.token-typeto change it.

Custom User Info RestTemplate

If the user-info-uriresource server internally using a OAuth2RestTemplateuser for authentication information to crawl, this is an id of userInfoRestTemplatethe @Beanoffer, but you do not need to know these, you can just use it. The default for most providers, but occasionally you may need to add additional interceptors, or change request validator (authenticator). Want to add custom, simply create a UserInfoRestTemplateCustomizertype of bean - it has only a single method, after the bean is created, initialized before the method is called. Here from rest template defined for internal use only perform authentication.

+

Note  Set RSA key in YAML, you need to use the pipe division multiple lines ( "|"), indent remember key value, such as:

Client

In order to put a web-app OAuth2 client, you only need to annotate @EnableOAuth2Client, Spring Boot created OAuth2ClientContextand OAuth2ProtectedResourceDetailsthat is to create OAuth2RestOperationsnecessary. Spring Boot does not automatically create the bean, but you do not create your own effort:

@Bean
public OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext,
        OAuth2ProtectedResourceDetails details) {
    return new OAuth2RestTemplate(details, oauth2ClientContext);
}

Note  that you may want to add a qualified name (qualifier), because it may define multiple applications RestTemplate.

This configuration uses security.oauth2.client.*a certificate (with the authorization to use the same server). In addition, it also needs to know URIs authorization and token authentication server, for example:

security:
    oauth2:
        client:
            clientId: bd1c0a783ccdd1c9b9e4
            clientSecret: 1a9030fbca47a5b2c28e92f19050bb77824b5ad1
            accessTokenUri: https://github.com/login/oauth/access_token
            userAuthorizationUri: https://github.com/login/oauth/authorize
            clientAuthenticationScheme: form

This configuration has application in use OAuth2RestTemplatewhen redirected to GitHub to complete the authorization, if already landed GitHub, you will not even notice that it has been authorized before. Those special credentials (credentials) valid only when the application is running on port 8080 (more flexible in order to register your own customers or other providers on GitHub end app).

 

Getting access token on the client side, you can set security.oauth2.client.scope(or a comma-separated YAML array) to limit the scope (scope) it requested. The default scope is empty, the default value depends on the authorization server, typically rely on its own client settings at the time of registration.

Note  to security.oauth2.client.client-authentication-schemealso set the default to "header" (if you do not like the header OAuth2 authentication provider, such as Github, you may need to set it to "form"). In fact, the security.oauth2.client.*property is bound to an AuthorizationCodeResourceDetailsinstance, so all of its properties can be specified.

Note  In a non-web application, you can create a still OAuth2RestOperations, and with the security.oauth2.client.*configuration association. In this case, it is a "client credentials token grant", if you use it, then you need to get (here no commentary @EnableOAuth2Clientor @EnableOAuth2Sso). In order to prevent the definition of infrastructure and need to security.oauth2.client.client-idbe removed from the configuration (or set it to an empty string).

 

security:
    oauth2:
        resource:
            jwt:
                keyValue: |
                    -----BEGIN PUBLIC KEY-----
                    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC...
                    -----END PUBLIC KEY-----

Single sign-on

OAuth2 client can be used to crawl from the provider user details, and then converted to Spring Security needs of the Authentication token. Mentioned by the resource server user-info-urito support this feature attribute, which is based on a single point OAuth2 login (SSO) protocol basic, Spring Boot provided @EnableOAuth2Ssonotes make it easier to practice. By adding the annotation and endpoint configuration ( security.oauth2.client.*), the client can use Github /user/endpoint protection of all its resources:

security:
    oauth2:
...
    resource:
        userInfoUri: https://api.github.com/user
        preferTokenInfo: false

Because all paths are in default under protection, there is no home to show those unauthorized users, and then invite them to log in (through access /loginpath, or security.oauth2.sso.login-paththe path specified).

To access path to the custom rules or protection (so you can add the home page), you can @EnableOAuth2Ssoadd to a WebSecurityConfigurerAdapter, the annotation will package it, enhanced where needed in order to make the /loginpath to work. For example, here we allow unauthorized users to access the home page /, the other still keep the default:

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void init(WebSecurity web) {
        web.ignore("/");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/**").authorizeRequests().anyRequest().authenticated();
    }

}

 

 

Actuator Safety

If Actuator is in use, you will find:

  • Endpoint Management is safe, even if the application endpoints secure.
  • Security events into AuditEvents, and publish to AuditService.
  • The default user ADMIN, USERrole.

Actuator security features can be configured through the external properties ( management.security.*) to be modified. In order to cover the application access rules but not covered by the access rules actuator, you can add a WebSecurityConfigurerAdaptertype @Bean, and comment @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER), if you want access rules covering the actuator, the annotations @Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER).

Guess you like

Origin blog.csdn.net/zhangbijun1230/article/details/91358545