Single point system -- token token parsing

Keywords: Back-end RESTful

Tokens are generated by JWT (Json Web Token - a json format). The default generation is in uuid format, but we need to override this method to generate JWT format. As a response token, it responds from the server to the client. After receiving the JWT token, the client saves it in the client (such as localStorage), and then carries the token to access the resource server. The resource server obtains and analyzes the legitimacy of the token, and determines whether the user is allowed to access the resource based on the analysis result

What objects are needed to implement an authentication and authorization system?

1. System resources -- data

2. Resource owner - user

3. Server for managing resources

4. A server that authenticates and authorizes users

5. Client system -- a system loaded with user identity information

For an authentication and authorization system:

1. Provide an authentication entry - where does the client go for authentication?

2. What information should the client carry to authenticate?

3. Through whom does the server authenticate the client - an object responsible for authentication?

Answer: create an authentication and authorization configuration class to inherit the adapter class AuthorizationServerConfigurerAdapter

Then rewrite the three methods:

1. Provide an authentication Portal -- the client authenticates here, as shown in the figure:

The following three attribute methods, tikenKeyAccess(); That is, the user will get a token after login authentication.

checkTokenAccess(): means that when a user accesses again, he can authenticate with a token, so he doesn't have to log in again.

@Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //super.configure(security);
        //Issue the authentication entry (/ oauth/token) to the outside world. If the authentication passes, the server will generate a token
        security.tokenKeyAccess("permitAll()")
                //The entry for issuing a check token (/ oauth/check_token)
                .checkTokenAccess("permitAll()")
                //Users are allowed to submit authentication through forms to complete authentication
                .allowFormAuthenticationForClients();
    }

  2. Define what information the client should carry to authenticate?

These identifications and keys are self-defined and can be changed.

Authorized grant types ("password", "refresh_token") -- specifies the authentication type. It can be password login or take the token obtained after successful login. The token has a time limit. You can set the refresh token, and the refreshed token can be authenticated

 @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        //super.configure(clients);
        clients.inMemory()
                //Client ID
                .withClient("gateway-client")
                //Client key (optional)
                .secret(passwordEncoder.encode("123456"))
                //Specify the authentication type (code secret, refresh token, third-party token,...)
                .authorizedGrantTypes("password","refresh_token")
                //Scope (it can be understood here that any client containing the information specified by us can be authenticated)
                .scopes("all");
    }

3. Provide an object responsible for authentication and authorization - a token will be issued after client authentication. The default format of the token is uuid, which is not secure. We use jwt format.

  //Provide an object responsible for authentication and authorization? (the token will be issued after the client authentication is completed. The default token format is uuid)
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //super.configure(endpoints);
        //Set authentication authorization object
        endpoints.authenticationManager(authenticationManager)
                //Set the token business object (this object provides token creation and effective mechanism settings)
                .tokenServices(tokenService())//No, the default is uuid
                //Set which request methods are allowed to be authenticated (post is supported by default): optional
                .allowedTokenEndpointRequestMethods(HttpMethod.GET,HttpMethod.POST);
    }

4. How tokens are generated

 @Bean
    public AuthorizationServerTokenServices tokenService(){
        //1. Build token business object
        DefaultTokenServices ts=new DefaultTokenServices();
        //2. Set the token generation mechanism (how to create a token and how to store user status information)
        ts.setTokenStore(tokenStore);
        //3. Set token enhancement (change the default token creation method. Without this sentence, the default is UUID)
        ts.setTokenEnhancer(jwtAccessTokenConverter);
        //4. Set token validity (optional)
        ts.setAccessTokenValiditySeconds(3600);
        //5. Set the refresh token and its effective duration (optional)
        ts.setSupportRefreshToken(true);
        ts.setRefreshTokenValiditySeconds(3600*24);
        return ts;
    }

tokenStore is used as the object to set the token generation mechanism - the method to create a token and the way to store user information-- Because this configuration class can also be called by other classes, a token configuration class is written separately

@Configuration
public class TokenConfig {//Resolve the token obtained by login authentication, and you can access resources consistently
    //jwt token signature key (the key used when the system bottom layer signs the header and payload parts of the token,
    //This key must be saved, and the client will not be informed)
    private String signingKey= "auth";//It can also be written to the configuration center later
    @Bean
    public JwtAccessTokenConverter tokenConverter(){
        JwtAccessTokenConverter tokenConverter=new JwtAccessTokenConverter();
        tokenConverter.setSigningKey(signingKey);//auth is the signature key
        return tokenConverter;
    }
    @Bean
    public TokenStore tokenStore(){
        JwtTokenStore tokenStore=new JwtTokenStore(tokenConverter());
        return tokenStore;
    }
}

Posted by rdawson on Fri, 03 Dec 2021 06:29:16 -0800