Spring security OAuth2 accept JSON

前端 未结 6 1841
深忆病人
深忆病人 2020-12-09 00:56

I am starting with Spring OAuth2. I would like to send the username and password to /oauth/token endpoint in POST body in application/json format.

curl -X PO         


        
6条回答
  •  眼角桃花
    2020-12-09 01:23

    From the OAuth 2 specification,

    The client makes a request to the token endpoint by sending the
    following parameters using the "application/x-www-form-urlencoded"

    Access token request should use application/x-www-form-urlencoded.

    In Spring security, the Resource Owner Password Credentials Grant Flow is handled by ResourceOwnerPasswordTokenGranter#getOAuth2Authentication in Spring Security:

    protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) {
        Map parameters = clientToken.getAuthorizationParameters();
        String username = (String)parameters.get("username");
        String password = (String)parameters.get("password");
        UsernamePasswordAuthenticationToken userAuth = new UsernamePasswordAuthenticationToken(username, password);
    

    You can send username and password to request parameter.

    If you really need to use JSON, there is a workaround. As you can see, username and password is retrieved from request parameter. Therefore, it will work if you pass them from JSON body into the request parameter.

    The idea is like follows:

    1. Create a custom spring security filter.
    2. In your custom filter, create a class to subclass HttpRequestWrapper. The class allow you to wrap the original request and get parameters from JSON.
    3. In your subclass of HttpRequestWrapper, parse your JSON in request body to get username, password and grant_type, and put them with the original request parameter into a new HashMap. Then, override method of getParameterValues, getParameter, getParameterNames and getParameterMap to return values from that new HashMap
    4. Pass your wrapped request into the filter chain.
    5. Configure your custom filter in your Spring Security Config.

    Hope this can help

提交回复
热议问题