Spring Security OAuth2 learning record

1, OAuth2.0
1. Concept
OAuth The protocol provides a secure, open and simple platform for user resource authorization Standard Specification . What is different from the previous authorization methods
OAuth The authorization will not make the third party touch the user's account information (such as user name and password), that is, the third party can use the user's user name and password without using the user's user name and password
You can apply for authorization to obtain the user resource, so OAuth It is open and safe.
2. Application scenario
(1) Authorized login of third-party applications: for example, log in to other platforms with wechat
(2) Native app authorization: all app request background interfaces need to carry Token information
(3) The front-end and back-end separation framework, the front-end requests background data, and oauth2 security authentication is required
3. oauth2.0 role:
(1) Resource Owner: usually a user. For example, "Zhang San" wants to log in to the microblog through wechat scanning code. The microblog needs Zhang San's wechat avatar and nickname, so "Zhang San" is both the Resource Owner.
(2) Third party application: also known as client. For example, microblog wants to obtain Zhang San's wechat avatar, nickname and other information. At this time, microblog is the client for wechat authentication server.
(3) Authentication server( Authorization server: authenticate the resource owner; Authorize the client to access the resource and generate a token.
(4) Resource Server: stores user resources. For example, wechat stores the user's Avatar and nickname; Verify the validity of the token.
(5) Service Provider: for example, wechat (including authentication server and resource server)
4. Abstract process
Process analysis:
(1) The client sends an authentication request (microblog, get Zhang San's wechat avatar and nickname)
(2) The resource owner (Zhang San) agrees to authorize
(3) The client obtains the authorization code and Token (wechat) from the authentication server
(4) The authentication server returns a Token
(5) The client carries a Token to obtain the protected resource
(6) The resource server returns protected resources
5. Four modes of Oauth2.0 (described in combination with the code)
(1) Authorization code mode
(2) Simplified mode
(3) Password mode
(4) Client mode
2, Spring Security implements Oauth2.0

1. Create Maven project

(1) POM file

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <relativePath/> <!-- lookup parent from repository -->
    <description>Demo project for Spring Boot</description>

        <!-- Spring Security,OAuth2 and JWT Correlation dependency-->

        <!--Web relevant-->


        <!--Mysql Connection drive-->




(2) Project structure

2. Code implementation (only the simplest implementation for the time being, which will be supplemented later)

(1) Create authentication server configuration class

package com.cmxy.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.stereotype.Component;

 * Authentication server configuration class
 * Role: configure which clients can access the currently configured server
@EnableAuthorizationServer //Mark as authentication server
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private PasswordEncoder passwordEncoder;

     * Configure client information that can access this authentication server
     * You can use JDBC or memory (the principle is not much different)
     * To facilitate the temporary use of memory based storage of client information
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()//Memory based mode
                .withClient("client")//client ID 
                .secret(passwordEncoder.encode("123456"))//The client secret key must be encrypted here. After spring security 5.0, the password must be encrypted.
                .resourceIds("product")//Accessible resource ID
                .scopes("user")//Accessible range
                //Authorization mode: that is, the authorization mode supported by the current authentication server in decibels is authorization code mode, password mode, client mode, simple mode and refresh Token
                .authorizedGrantTypes("authorization_code", "password", "client_credentials", "implicit", "refresh_token")
                .autoApprove(false)//Whether to authorize automatically. Generally, if it is set to false, it means that the user needs to authorize manually
                .redirectUris("www.baidu.com");//Redirect path


(2) Create Spring Security configuration class

package com.cmxy.oauth2.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private PasswordEncoder passwordEncoder;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

(3) Configure the encryption method (after spring security 5.0, password encryption is required)

package com.cmxy.oauth2.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class SpringSecurityBean {

    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();

3. Interface test

The first test is the authorization code mode

Authorization code mode:

The authorization mode with the most complete functions and the most rigorous process. Major domestic service providers (wechat, QQ, microblog, Taobao and Baidu) use this mode for authorization. It can be determined that the user really agrees to the authorization; Moreover, the token is issued by the authentication server to the server of the third-party application, not on the browser.

(1) Enter the url in the browser: http://localhost:8080/oauth/authorize?client_id=client&response_type=code

Including: client_id is configured in the configuration class, and the type of response is authorization code

(2) At this time, because you have not logged in before, you will jump to the landing page

Note that the account password here belongs to the resource owner, not the client!!! In this demo, the account is admin and the password is 123456

After successful login, jump to the authorization page (is it a little similar to wechat authorization)

  (3) If you select authorization, you will jump to the previously configured redirection path, that is, Baidu


  Note that the authorization code is included at this time. Finally, take the authorization code to replace the token. Each authorization code can only be used once.

(4) Get Token



  Finally, carry the Token to request the corresponding resource. So far, the most complex authorization code mode has been completed

Unfinished to be continued...

Tags: Java Spring Spring Boot

Posted on Wed, 20 Oct 2021 02:55:07 -0400 by JKinBlack