import java.security.Principal;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 用于oauth获取token,功能等同于密码模式下直接调用url /oauth/token 获取token
* @author lenovo
*
*/
@RequestMapping("/getToken")
@RestController
public class OauthPasswordPatternGetToken {
@Autowired
TokenEndpoint tokenEndPoint;
/**
* 功能等同于 /oauth/token 获取的token
* @param principal 自动赋值的对象
* @return
* @throws HttpRequestMethodNotSupportedException
*/
@PostMapping
public ResponseEntity<OAuth2AccessToken> getToken(Principal principal) throws HttpRequestMethodNotSupportedException {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("client_id", "peter");
parameters.put("client_secret", "hello");
parameters.put("grant_type", "password");
parameters.put("username", "peter");
parameters.put("password", "hello");
// 直接调用 /oauth/token 映射的方法,不在通过url调用获取token
ResponseEntity<OAuth2AccessToken> result = tokenEndPoint.getAccessToken(principal, parameters);
return result;
}
}
Spring Boot 使用Oauth2 密码模式 自定义接口获取token
最新推荐文章于 2024-09-13 22:25:48 发布