SpringBoot Learning (Five) RSocket and Security

A, RSocket
RSocket byte is a binary protocol for streaming. It supports interaction model symmetry passing through asynchronous messaging on a single connection, the communication layer comprises a primary support TCP, WebSockets and Aeron (UDP).
RSocket mainly uses asynchronous message model communicate, solve all asynchronous message exchange through a single connection. Communication includes the following models:
  • request / response: a request / response, issues a request to obtain a response
  • request / stream: Request / Response stream, over one / numerous flow response corresponding to the request
  • fire-and-forget: asynchronous trigger, no response
  • channel (bi-directional streams): two-way asynchronous communication, which is the channel support
Spring Spring Framework messaging module in the client and server support RSocket requester and responder. For more details, please refer to the section RSocket Spring framework reference, including an overview of RSocket agreement.
1.1RSocket policies to automatically configure
Spring Boot automatically configure RSocketStrategies bean, it offers all the infrastructure to encode and decode the payload RSocket required. By default, will try to configure the automatic configuration (in order):
The decoder a.Jackson CBOR
The decoder b.Jackson JSON
spring-boot-starter-rsocket starters provide these dependencies.
Developers can be achieved by creating custom components RSocketStrategies bean rsocketstrateescustomizer interface. Pay attention to their @Order is important because it determines the order of codecs.
1.2RSocket server automatic configuration
Spring Boot RSocket server provides automatic configuration. Required dependencies provided by spring-boot-starter-rsocket. 
Spring Boot allowed by the server from WebFlux WebSocket RSocket exposure, or support independent RSocket server. Depending on the type and configuration of the application.
For WebFlux application (i.e. type WebApplicationType.REACTIVE), RSocket server only if the following attributes match will be inserted into the Web server:
spring.rsocket.server.mapping-path=/rsocket # a mapping path is defined
spring.rsocket.server.transport=websocket # websocket is chosen as a transport
#spring.rsocket.server.port= # no port is defined

Note: Only Reactor Netty was supported RSocket insert web server, because RSocket itself is built using this library.

Alternatively, RSocket TCP server or as a stand-alone embedded websocket server startup. In addition to rely on demand, the only configuration required is for the server to define a port:

spring.rsocket.server.port=9898 # the only required configuration
spring.rsocket.server.transport=tcp # you're free to configure other properties

1.3Spring messaging support RSocket

Spring will automatically configure the Boot Spring messaging infrastructure for RSocket.

This means that Spring Boot will create a RSocketMessageHandler bean, RSocket request for processing applications.

1.4 RSocketRequester RSocket call service

Once established RSocket passage between server and client, either party may request the other party to send or receive.

As a server, may be injected in any instance RSocketRequester handler method of RSocket @Controller. As a client, you first need to configure and build RSocket connection. Spring Boot automatically configure a RSocketRequester. With the expected construct codec such cases.

RSocketRequester.Builder example is a prototype bean, which means that each injection point will provide you with a new instance. This is done on purpose, because the builder is stateful, you should not create the requestor with different settings use the same instance.

The following code shows a typical example:

@Service
public class MyService {

    private final RSocketRequester rsocketRequester;

    public MyService(RSocketRequester.Builder rsocketRequesterBuilder) {
        this.rsocketRequester = rsocketRequesterBuilder
                .connectTcp("example.org", 9898).block();
    }

    public Mono<User> someRSocketCall(String name) {
        return this.requester.route("user").data(name)
                .retrieveMono(User.class);
    }

}

Second, security

If there is Spring Security on the class path, then by default the web application is secure. Spring Boot dependent on the content negotiation strategies Spring Security to decide whether to use httpBasic or formLogin. To add a method-level security to web applications, you can also use the settings you want to add @EnableGlobalMethodSecurity. Additional information can be found in the Spring Security Reference Guide.

The default UserDetailsService only one user. The user name is user, the password is random, the INFO level printing application startup, the following example shows:

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

NOTE: If you log configuration fine-tuning, make sure org.springframe .boot.autoconfigure.security category is set to INFO level messages. Otherwise, it will not print the default password.

You can change the user name and password by providing spring.security.user.name and spring.security.user.password.

By default, the basic characteristics of the web application are as follows:

a. a UserDetailsService (ReactiveUserDetailsService or WebFlux application) bean, and having a memory storing a user-generated password (see user attributes SecurityProperties.User).

B. form-based login security or HTTP substantially the entire application (depending on the Accept header in the request) (including the end actuator, if the actuator is located on the classpath).

c. for publishing authentication DefaultAuthenticationEventPublisher events.

You can provide a different AuthenticationEventPublisher by adding a bean for it.

1.MVC security

The default security configuration is implemented in SecurityAutoConfiguration and UserDetailsServiceAutoConfiguration in. SecurityAutoConfiguration configure authentication for web security and UserDetailsServiceAutoConfiguration, which is also associated with non-web applications. To turn off the default web application security configuration, or a combination of more Spring security components (such as OAuth 2 client and the resource server), add WebSecurityConfigurerAdapter type of bean (This will not disable the security UserDetailsService configuration or actuator) .

To turn off UserDetailsService configuration, you can add UserDetailsService, AuthenticationProvider or AuthenticationManager type of bean.

Access rules can be overridden by adding WebSecurityConfigurerAdapter custom. Spring Boot provides a convenient method can be used to cover the actuator endpoints and access rules static resources. EndpointRequest can be used to create a request based management.endpoints.web matching program. Base path property. You can create a RequestMatcher resource use PathRequest common position.

2.WebFlux security

Similar to the Spring MVC application, you can add Spring -boot-starter-security dependencies to protect WebFlux applications. The default security configuration is implemented in ReactiveSecurityAutoConfiguration and UserDetailsServiceAutoConfiguration in. ReactiveSecurityAutoConfiguration configure authentication for web security and UserDetailsServiceAutoConfiguration, which is also associated with non-web applications. To turn off the default web application security configuration, you can add WebFilterChainProxy type of bean (This will not disable the security UserDetailsService configuration or actuator).

To turn off UserDetailsService configuration, you can add or ReactiveAuthenticationManager ReactiveUserDetailsService type of bean.

By adding a custom SecurityWebFilterChain bean, you can configure access rules and use multiple Spring security components, such as OAuth 2 client and server resources. Spring Boot provides a convenient method can be used to cover the actuator endpoints and access rules static resources.

EndpointRequest can be used to create a basis management.endpoints.web of management.endpoints.web.base-path property.

You can create a ServerWebExchangeMatcher use PathRequest for the common position of the resource.

 

For example, you can customize your 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();
}

3.OAuth2

OAuth2 authorization framework is supported by a Spring widely used.

3.1 Client

If there are spring-security-oauth2-client on your class path, then you can use some automatic configuration to easily set OAuth2 / Open ID connecting client. This configuration uses the attributes of OAuth2ClientProperties. Apply to the same property and reactivity servlet application.

You can register multiple clients and in OAuth2 under spring.security.oauth2.client prefix provider. Client prefix, as shown in the following example:

spring.security.oauth2.client.registration.my-client-1.client-id=abcd
spring.security.oauth2.client.registration.my-client-1.client-secret=password
spring.security.oauth2.client.registration.my-client-1.client-name=Client for user scope
spring.security.oauth2.client.registration.my-client-1.provider=my-oauth-provider
spring.security.oauth2.client.registration.my-client-1.scope=user
spring.security.oauth2.client.registration.my-client-1.redirect-uri=https://my-redirect-uri.com
spring.security.oauth2.client.registration.my-client-1.client-authentication-method=basic
spring.security.oauth2.client.registration.my-client-1.authorization-grant-type=authorization_code

spring.security.oauth2.client.registration.my-client-2.client-id=abcd
spring.security.oauth2.client.registration.my-client-2.client-secret=password
spring.security.oauth2.client.registration.my-client-2.client-name=Client for email scope
spring.security.oauth2.client.registration.my-client-2.provider=my-oauth-provider
spring.security.oauth2.client.registration.my-client-2.scope=email
spring.security.oauth2.client.registration.my-client-2.redirect-uri=https://my-redirect-uri.com
spring.security.oauth2.client.registration.my-client-2.client-authentication-method=basic
spring.security.oauth2.client.registration.my-client-2.authorization-grant-type=authorization_code

spring.security.oauth2.client.provider.my-oauth-provider.authorization-uri=https://my-auth-server/oauth/authorize
spring.security.oauth2.client.provider.my-oauth-provider.token-uri=https://my-auth-server/oauth/token
spring.security.oauth2.client.provider.my-oauth-provider.user-info-uri=https://my-auth-server/userinfo
spring.security.oauth2.client.provider.my-oauth-provider.user-info-authentication-method=header
spring.security.oauth2.client.provider.my-oauth-provider.jwk-set-uri=https://my-auth-server/token_keys
spring.security.oauth2.client.provider.my-oauth-provider.user-name-attribute=name

Support for OpenID OpenID provider connections connecting discovery, configuration can be further simplified. Providers need to configure a publisher URI, the URI is a statement of its issuer identifier. For example, if the issuer uri provide a "https://example.com", it will "https://example.com/.known/openid - Configuration" OpenID provider issuing a configuration request. The expected result is an OpenID provider configuration response. The following example shows how to use the publisher uri configuration OpenID Provider connection:

spring.security.oauth2.client.provider.oidc-provider.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/

By default, Spring Security OAuth2LoginAuthenticationFilter only the matching process / login / oauth2 / code / * the url. If you want to customize redirect-uri to use a different mode, the need to provide custom configured to process mode. For example, for a servlet application, you can add your own WebSecurityConfigurerAdapter, as follows:

public class OAuth2LoginSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .oauth2Login()
                .redirectionEndpoint()
                    .baseUri("/custom-callback");
    }
}

OAuth2 client ordinary registered provider

For the common OAuth2 and OpenID providers, including Google, Github, Facebook and Okta, we provide a set of default values ​​providers (Google, respectively, Github, Facebook and Okta).

If these do not need to provide a custom program, the provider may be required to infer the attribute property to default values. In addition, if the client registers the key with the default provider supported match, Spring Boot will deduce it.

 

In other words, in the following example configuration uses two Google Provider:

spring.security.oauth2.client.registration.my-client.client-id=abcd
spring.security.oauth2.client.registration.my-client.client-secret=password
spring.security.oauth2.client.registration.my-client.provider=google

spring.security.oauth2.client.registration.google.client-id=abcd
spring.security.oauth2.client.registration.google.client-secret=password

3.2 server resources

If there is Spring -security- OAuth2 on your class path - Resource - Server, Spring Boot OAuth2 can set up a resource server. For JWT configuration, specify JWK Set URI or the URI OIDC issuer, the following example:

spring.security.oauth2.resourceserver.jwt.jwk-set-uri=https://example.com/oauth2/default/v1/keys
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://dev-123456.oktapreview.com/oauth2/default/

Note: If the license server does not support URI JWK settings, you can use the public key used to verify the signature JWT to configure server resources. This can be done using spring.security.oauth2.resourceserver.jwt. Public location attribute, which values need to point to a file containing the public key peme x509 encoding format.

Apply to the same property and reactivity servlet application.

 

Alternatively, you can define your own servlet application JwtDecoder bean, or define ReactiveJwtDecoder reactive applications.

In the case of an opaque token instead JWTs, you can configure the following properties through introspection authentication token:

spring.security.oauth2.resourceserver.opaquetoken.introspection-uri=https://example.com/check-token
spring.security.oauth2.resourceserver.opaquetoken.client-id=my-client-id
spring.security.oauth2.resourceserver.opaquetoken.client-secret=my-client-secret

Similarly, servlet, and the reaction of the applications are applicable to the same property.

 

Alternatively, you can define your own opaquetokenintrotor bean as a servlet application, or define a reactiveopaquetokenintrotor as reactive applications.

3.3 Authorization Server

Currently, Spring Security does not support the achievement of OAuth 2.0 authorization server. However, this feature is available from Spring Security OAuth project, Spring Security will eventually completely replace it. Until then, you can use spring-security- oau2 -autoconfigure module easily set up OAuth 2.0 Authorization Server; For instructions, see its documentation.

4.SAML 2.0
4.1 relying party
If there are spring-security-saml2-service-provider based on your path, you can use a number of automatic configuration settings to simplify SAML 2.0 relying party. This configuration uses the attributes Saml2RelyingPartyProperties.
Sign up relying party arranged in pairs between the identity provider (IDP) and service provider (SP). You can register multiple relying parties in spring.security.saml2. Prefix reproducing side, as shown in the following example:
spring.security.saml2.relyingparty.registration.my-relying-party1.signing.credentials[0].private-key-location=path-to-private-key
spring.security.saml2.relyingparty.registration.my-relying-party1.signing.credentials[0].certificate-location=path-to-certificate
spring.security.saml2.relyingparty.registration.my-relying-party1.identityprovider.verification.credentials[0].certificate-location=path-to-verification-cert
spring.security.saml2.relyingparty.registration.my-relying-party1.identityprovider.entity-id=remote-idp-entity-id1
spring.security.saml2.relyingparty.registration.my-relying-party1.identityprovider.sso-url=https://remoteidp1.sso.url

spring.security.saml2.relyingparty.registration.my-relying-party2.signing.credentials[0].private-key-location=path-to-private-key
spring.security.saml2.relyingparty.registration.my-relying-party2.signing.credentials[0].certificate-location=path-to-certificate
spring.security.saml2.relyingparty.registration.my-relying-party2.identityprovider.verification.credentials[0].certificate-location=path-to-other-verification-cert
spring.security.saml2.relyingparty.registration.my-relying-party2.identityprovider.entity-id=remote-idp-entity-id2
spring.security.saml2.relyingparty.registration.my-relying-party2.identityprovider.sso-url=https://remoteidp2.sso.url

The actuator safety

For security reasons, all actuators except / health and / info are disabled by default. management.endpoints.web.exposure. include properties for enabling the actuator.

If Spring Security on the class path, and no other WebSecurityConfigurerAdapter exist, in addition to / health and / info all actuators automatically configured by the guide Spring protected. If you define a custom WebSecurityConfigurerAdapter, Spring will automatically configure the boot back, you will totally control access rules drive.
Note: In setting management.endpoints.web.exposure.include before. The actuators are not exposed to ensure that sensitive information and / or behind a firewall to protect them or by something Spring Security or the like by placing them on.
5.1 Cross-site request forgery protection
Since Spring Boot Spring Security rely on the default values, so by default CSRF protection is opened. This means that, when using the default security configuration, the actuator endpoints need to POST (shutdown and loggers endpoint), PUT or DELETE will get a 403 Forbidden error.
Note: We recommend that only completely disable CSRF protection when you create the service non-browser used by the client.
For more information about CSRF protection can be found in the Spring Security Reference Guide.
 
 

 

Guess you like

Origin www.cnblogs.com/muxi0407/p/12077448.html