所以我想我解决了我的问题。如果有人偶然发现相同的问题,我将在此处发布解决方案:
正如 Play-Docs (https://www.playframework.com/documentation/2.6.x/JavaOAuth) 中所写,使用 OAuth2 尤其是使用密码流程时,它非常简单。
首先你需要一个授权服务,这里的实现很简单。只需实现三个方法:
POST /oauth/token 用于传递用户凭据并接收访问和刷新令牌
POST /oauth/refresh 当访问令牌不再有效时。这里传递了刷新令牌并返回了一个新的访问令牌
POST /oauth/check_token 进行授权。这里传递了访问令牌,在我的情况下,我返回了用户拥有的角色。或者,在授权服务中进行授权过程也是可能的,甚至更好。为此,您需要更改“check_token”方法并传递所需的角色。
我只是将 uuids 生成为令牌并将它们存储在数据库中。我想也可以使用例如 jwts 并将所需的信息(例如到期日期)放入令牌中。
然后我的主要问题是关于注释的。我找到了这个
https://github.com/bekce/oauthly
看看他们的实现。
你基本上只需要一个类和一个接口:
界面:
@With(AuthorizationServerAuthAction.class)
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthorizationServerSecure {
boolean requireAdmin() default false;
boolean requirePersonnel() default false;
boolean requireGuest() default false;
}
班级:
private WSClient ws;
private final String url = "http://localhost:9001/oauth/check_token";
@Inject
public AuthorizationServerAuthAction(WSClient ws) {
this.ws = ws;
}
private CompletionStage<JsonNode> callApi(String accessToken) {
CompletionStage<WSResponse> eventualResponse = ws.url(url).setContentType("application/x-www-form-urlencoded").setRequestTimeout(Duration.ofSeconds(10))
.addHeader("Authorization" , accessToken).post("none");
return eventualResponse.thenApply(WSResponse::asJson);
}
@Override
public CompletionStage<Result> call(Http.Context ctx) {
Optional<String> accessTokenOptional = ctx.request().header("Authorization");
JsonNode result = null;
if(!accessTokenOptional.isPresent()){
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "No token found in header!")
));
}
CompletionStage<JsonNode> apiResponse = callApi(accessTokenOptional.get());
try {
result = apiResponse.toCompletableFuture().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if(result == null) {
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "an error occurred")
));
}
String role = result.get("role").asText();
if(configuration.requireAdmin()){
if(role.equals("admin")) {
return delegate.call(ctx);
} else {
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "The user is not authorized to perform this action!")
));
}
} else if(configuration.requirePersonnel()) {
if(role.equals("personnel") || role.equals("admin")) {
return delegate.call(ctx);
} else {
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "The user is not authorized to perform this action!")
));
}
} else if(configuration.requireGuest()) {
if(role.equals("guest") || role.equals("personnel") || role.equals("admin")) {
return delegate.call(ctx);
} else {
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "The user is not authorized to perform this action!")
));
}
}
return CompletableFuture.completedFuture(unauthorized(Json.newObject()
.put("message", "an error occurred")
));
}
}