How to secure REST API with Spring Boot and Spring Security?

后端 未结 4 1611
抹茶落季
抹茶落季 2020-12-02 04:58

I know that securing REST API is widely commented topic but I\'m not able to create a small prototype that meets my criteria (and I need to confirm that these criteria are r

4条回答
  •  执念已碎
    2020-12-02 05:14

    Spring security also very useful for providing authentication and authorization to the REST URLs. We no need to specify any custom implementations.

    First, you need to specify the entry-point-ref to restAuthenticationEntryPoint in your security configuration as below.

     
    
        
        
        
    
    

    Implementation for the restAuthenticationEntryPoint might be as below.

     @Component
    public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    
       public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException ) throws IOException {
          response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
       }
    }
    

    After this you need to specify RequestHeaderAuthenticationFilter. It contains the RequestHeader key. This is basically used for identifying the user`s authentication. Generally RequestHeader carries this information while making the REST calls. For example consider below code

       
        
        
      
    

    Here,

    
    

    "Authorization" is the the key presented the incoming request. It holds the required user`s authentication information. Also you need to configure the PreAuthenticatedAuthenticationProvider to fulfill our requirement.

       
    
      
        
      
    
    
    

    This code will work for securing the REST urls by means of Authentication and authorization without any custom implementations.

    For Complete code please find the below link:

    https://github.com/srinivas1918/spring-rest-security

提交回复
热议问题