Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
1
Indexable
Never
@FrameworkEndpoint
@RequestMapping("/access-token/b2b")
public class CustomTokenEndpoint extends AbstractEndpoint implements InitializingBean, ApplicationContextAware {

    private ClientCredentialsTokenGranter tokenGranter;

    private OAuth2RequestValidator oAuth2RequestValidator;

    private OAuth2RequestFactory oAuth2RequestFactory;

    @Autowired
    public void setTokenGranter(ClientCredentialsTokenGranter tokenGranter) {
        this.tokenGranter = tokenGranter;
    }

    @Autowired
    public void setoAuth2RequestValidator(OAuth2RequestValidator oAuth2RequestValidator) {
        this.oAuth2RequestValidator = oAuth2RequestValidator;
    }

    @Autowired
    public void setoAuth2RequestFactory(OAuth2RequestFactory oAuth2RequestFactory) {
        this.oAuth2RequestFactory = oAuth2RequestFactory;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<OAuth2AccessToken> postAccessToken(@RequestBody Map<String, String> parameters) {
        String clientId = parameters.get("client_id");
        if (clientId == null) {
            throw new InvalidClientException("No client id provided");
        }
        ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId);
        TokenRequest tokenRequest = new ClientCredentialsTokenRequest(oAuth2RequestFactory.createOAuth2Request(authenticatedClient, parameters));
        oAuth2RequestValidator.validateScope(tokenRequest, authenticatedClient);
        OAuth2AccessToken token = tokenGranter.grant("client_credentials", tokenRequest);
        if (token == null) {
            throw new UnsupportedGrantTypeException("Unsupported grant type: client_credentials");
        }
        return getResponse(token);
    }

    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<String> getAccessToken(@RequestBody Map<String, String> parameters) {
        return new ResponseEntity<String>("Method Not Allowed", HttpStatus.METHOD_NOT_ALLOWED);
    }

    @RequestMapping(method = RequestMethod.OPTIONS)
    public ResponseEntity<String> optionsAccessToken(@RequestBody Map<String, String> parameters) {
        return new ResponseEntity<String>("OK", HttpStatus.OK);
    }

    private ResponseEntity<OAuth2AccessToken> getResponse(OAuth2AccessToken accessToken) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        headers.setContentType(MediaType.APPLICATION_JSON);
        return new ResponseEntity<OAuth2AccessToken>(accessToken, headers, HttpStatus.OK);
    }
}
Leave a Comment