Spring Security Learning (Xi, spring MVC interview questions often asked 2020)

Posted by Johan Beijar on Tue, 21 Dec 2021 22:48:34 +0100

Spring social introduced in previous blogs encapsulates third-party applications, goes to service providers and obtains user information through OAuth protocol. Here we need to complete the logic development of the service provider, so we need to use spring security OAuth

Using spring security OAuth, we can quickly build the logic of the service provider, provide token s and verify them.

As a service provider, you need two pieces of content, one is the authentication server and the other is the resource server. In fact, the so-called authentication server can be simply understood as the logic of generating token. The so-called resource server is our business code. These two are just a logical concept, not two physically independent servers.

Simple example

==================================================================

We still implement the relevant examples in the original project. For the code organization structure of the examples, please refer to our previous blog—— Introduction to spring -security.

preparation

The example of this blog will be completed in the App module. Meanwhile, the reference of demo needs to be modified to apply App, as shown below:

<dependencies>

    <dependency>

        <groupId>com.coderman.learn</groupId>

        <artifactId>spring-security-core</artifactId>

        <version>${self.app.version}</version>

    </dependency>

</dependencies> 

At the same time, prepare a business interface to obtain user information

@GetMapping("/me")

public Object getCurrentUser(@AuthenticationPrincipal UserDetails userDetails){

    log.info("user me test");

    return userDetails;

} 

The previously customized UserDetailsService also needs to exist

/**

 * autor:liman

 * createtime:2021/7/8

 * comment:

 */

@Component

@Slf4j

public class MyUserDetailService implements UserDetailsService{



    @Autowired

    private PasswordEncoder passwordEncoder;



    /**

     * Find user information by user name

     * @param username

     * @return

     * @throws UsernameNotFoundException

     */

    @Override

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        log.info("Find user information by user name:{}",username);

        return new User(username,passwordEncoder.encode("123456"),

                true,true,true,true,

                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));

    }

} 

In order to avoid the tedious task of inputting the clientid every time you restart, configure the clientid and clientsecret in the configuration file

security.oauth2.client.clientId=selfclientid

security.oauth2.client.clientSecret=selfclientsecret 

Implement authentication server

Recall the function of the authentication server in social login (taking the authorization code login as an example), you need to generate the authorization code based on the OAuth2 protocol and attach the authorization code to the callback address configured by the third-party application. Then the third-party application exchanges the token according to the obtained authorization code, and finally obtains the corresponding user information according to the token.

Based on spring security oauth, this is not difficult, and several configurations are completed.

/**

 * autor:liman

 * createtime:2021/7/22

 * comment: app Authentication server configuration class

 *

 */

@Configuration

@EnableAuthorizationServer

public class AppAuthorizationServerConfig {

} 

Obtain authorization code

At this time, our application has the function of authentication server. When the project starts, we will find that spring security oauth adds several request paths starting with oauth for us, as shown below:

These request paths are the corresponding OAuth access paths. We can access oauth/authorize according to the relevant protocol parameters of OAuth2. For the protocol request parameters of OAuth2, please refer to Chapter 4 of the OAuth2 official website—— OAuth2 protocol official website.

Enter the following path in the browser

http://localhost:8090/oauth/authorize?response_type=code&client_id=selfclientid&redirect_uri=http://example.com&scope=all 

The callback path configured here is http://expample.com ,client_id is the clientid configured in our preparations, which actually indicates the third-party application number, response_ The type is fixed as code, and the scope is specified as all. These are described in detail on the OAuth2 official website.

After entering the above address in the browser, the authentication dialog box will pop up

Why does the authentication dialog box pop up? Because the authentication server needs to determine which user in the third-party application is authorizing, we need to enter relevant user information. The authentication of user information is MyUserDetailService customized before. In our example, we only need to ensure that the user password is 123456. Normally, after entering the user name and password, It will jump to the authorization page. But

***

@Override

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

    log.info("Find user information by user name:{}",username);

    return new User(username,passwordEncoder.encode("123456"),

            true,true,true,true,

            AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_USER"));

} 

After that, restart the system (re-enter the user name and password if necessary) to see the authorization page, as shown in the following dynamic diagram

After clicking Approval on the authorization page, you will see that the browser displays the callback url with the authorization code attached. Then you can obtain the token according to the authorization code

Obtain the token according to the authorization code

This step can be completed with postman, specifying the request path as / oauth/token (I have configured the relevant host file, so I don't need to enter ip and port)

The clientid and clientSecret configured by us need to be added to the Basic Auth authentication information, and the authorization code needs to be added to the body

Finally, summarize my interview experience

The gold, silver and silver in 2021 will arrive in the blink of an eye. For many people, it is a good opportunity to change jobs. The interview in large factories is far less difficult than we think. You can set your mind and prepare well.

In addition, you might as well try to talk about your own ideas for the problems you won't encounter in the interview, because some problems don't examine our programming ability, but our logical thinking and expression ability; Finally, we should conduct self-analysis and evaluation, make career planning, constantly explore, and improve our programming ability and abstract thinking ability.

Data collection method: Click here for free

BAT interview experience

Actual combat series: Spring family bucket + Redis, etc

Other related e-books: source code + tuning

Interview questions:

n.net/m0_60958482/java-p7)**

[external chain picture transferring... (img-6gebmkic-16292416799)]

BAT interview experience

Actual combat series: Spring family bucket + Redis, etc

[external chain picture transferring... (img-3yr99ryu-16292416801)]

Other related e-books: source code + tuning

[external chain picture transferring... (img-xsczf5gl-16292416802)]

Interview questions:

[external chain picture transferring... (img-4znrvwjq-16292416803)]

[external chain picture transferring... (img-yh0psowz-16292416804)]

Topics: Java Interview Programmer