Apache olth学习笔记
简介
代码结构
- issuser 主要提供用于生成授权码(authorization code)、访问令牌(access token)和刷新令牌(refresh token)的通用实现
- request 用于封装授权码请求和令牌请求的通用逻辑,并提供响应的校验手段
- response 用于封装授权流程中通用的响应逻辑,提供生成不同响应结果的方法
- validator 为request提供校验服务
issuser代码分析
public String accessToken() throws OAuthSystemException;
public String authorizationCode() throws OAuthSystemException;
public String refreshToken() throws OAuthSystemException;
}
public String generateValue() throws OAuthSystemException;
public String generateValue(String param) throws OAuthSystemException;
}
request代码分析
try {
// 拿到validator
validator = initValidator();
validator.validateMethod(request);
validator.validateContentType(request);
// 校验必填的参数是否满足
validator.validateRequiredParameters(request);
// 校验凭证认证
validator.validateClientAuthenticationCredentials(request);
} catch (OAuthProblemException e) {
try {
String redirectUri = request.getParameter(OAuth.OAUTH_REDIRECT_URI);
if (!OAuthUtils.isEmpty(redirectUri)) {
e.setRedirectUri(redirectUri);
}
} catch (Exception ex) {
if (log.isDebugEnabled()) {
log.debug("Cannot read redirect_url from the request: {}", new String[] {ex.getMessage()});
}
}
throw e;
}
}
// 请求授权码时response_type参数可以是code或token,详情看oauth2.0规范
validators.put(ResponseType.CODE.toString(), CodeValidator.class);
validators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
// 从实际请求中获取response_type参数,跟根据其值返回对应的validator实例
final String requestTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE);
if (OAuthUtils.isEmpty(requestTypeValue)) {
throw OAuthUtils.handleOAuthProblemException("Missing response_type parameter value");
}
final Class<? extends OAuthValidator<HttpServletRequest>> clazz = validators.get(requestTypeValue);
if (clazz == null) {
throw OAuthUtils.handleOAuthProblemException("Invalid response_type parameter value");
}
return OAuthUtils.instantiateClass(clazz);
}
validator代码分析
public void validateMethod(T request) throws OAuthProblemException;
public void validateContentType(T request) throws OAuthProblemException;
public void validateRequiredParameters(T request) throws OAuthProblemException;
public void validateOptionalParameters(T request) throws OAuthProblemException;
public void validateNotAllowedParameters(T request) throws OAuthProblemException;
public void validateClientAuthenticationCredentials(T request) throws OAuthProblemException;
public void performAllValidations(T request) throws OAuthProblemException;
}
protected List<String> requiredParams = new ArrayList<String>();
// 可选字段列表
protected Map<String, String[]> optionalParams = new HashMap<String, String[]>();
// 不允许出现字段列表
protected List<String> notAllowedParams = new ArrayList<String>();
// 是否必须进行权限认证
protected boolean enforceClientAuthentication;
final Set<String> missingParameters = new HashSet<String>();
for (String requiredParam : requiredParams) {
String val = request.getParameter(requiredParam);
if (OAuthUtils.isEmpty(val)) {
missingParameters.add(requiredParam);
}
}
if (!missingParameters.isEmpty()) {
throw OAuthUtils.handleMissingParameters(missingParameters);
}
}
public CodeValidator() {
requiredParams.add(OAuth.OAUTH_RESPONSE_TYPE);
requiredParams.add(OAuth.OAUTH_CLIENT_ID);
}
@Override
public void validateMethod(HttpServletRequest request) throws OAuthProblemException {
String method = request.getMethod();
if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) {
throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST)
.description("Method not correct.");
}
}
@Override
public void validateContentType(HttpServletRequest request) throws OAuthProblemException {
}
}
response代码分析
ResponseBuilder代码分析
OAuthResponse oAuthResponse= OAuthASResponse.authorizationResponse(request, 200)
.location(jdUrl)
.setCode(oauthCode)
.setScope(state)
.buildQueryMessage();
String url=oAuthResponse.getLocationUri();
response.sendRedirect(url);
// 访问令牌
OAuthResponse authASResponse = OAuthASResponse.tokenResponse(200)
.setAccessToken(access_token)
.setExpiresIn("7200")
.setRefreshToken(refreshToken)
.setTokenType(TokenType.BEARER.toString())
.setParam("re_expires_in", "14400")
.buildJSONMessage();
String json= authASResponse.getBody();
// 错误响应
OAuthResponse authASResponse = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
.setError(OAuthError.ResourceResponse.INVALID_TOKEN)
.setErrorDescription("invald expired")
.buildJSONMessage();
return new ResponseEntity<String>(authASResponse.getBody(), headers, HttpStatus.UNAUTHORIZED);
protected OAuthParametersApplier applier;
protected Map<String, Object> parameters = new HashMap<String, Object>();
protected int responseCode;
protected String location;
public OAuthResponseBuilder(int responseCode) {
this.responseCode = responseCode;
}
public OAuthResponseBuilder location(String location) {
this.location = location;
return this;
}
public OAuthResponseBuilder setScope(String value) {
this.parameters.put(OAuth.OAUTH_SCOPE, value);
return this;
}
public OAuthResponseBuilder setParam(String key, String value) {
this.parameters.put(key, value);
return this;
}
public OAuthResponse buildQueryMessage() throws OAuthSystemException {
OAuthResponse msg = new OAuthResponse(location, responseCode);
this.applier = new QueryParameterApplier();
if (parameters.containsKey(OAuth.OAUTH_ACCESS_TOKEN)) {
this.applier = new FragmentParametersApplier();
}else{
this.applier = new QueryParameterApplier();
}
return (OAuthResponse)applier.applyOAuthParameters(msg, parameters);
}
public OAuthResponse buildBodyMessage() throws OAuthSystemException {
OAuthResponse msg = new OAuthResponse(location, responseCode);
this.applier = new BodyURLEncodedParametersApplier();
return (OAuthResponse)applier.applyOAuthParameters(msg, parameters);
}
public OAuthResponse buildJSONMessage() throws OAuthSystemException {
OAuthResponse msg = new OAuthResponse(location, responseCode);
this.applier = new JSONBodyParametersApplier();
return (OAuthResponse)applier.applyOAuthParameters(msg, parameters);
}
public OAuthResponse buildHeaderMessage() throws OAuthSystemException {
OAuthResponse msg = new OAuthResponse(location, responseCode);
this.applier = new WWWAuthHeaderParametersApplier();
return (OAuthResponse)applier.applyOAuthParameters(msg, parameters);
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。