Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
实现OAuth2的密码所有者资源流(Java)_Java_Playframework_Oauth 2.0_Authorization - Fatal编程技术网

实现OAuth2的密码所有者资源流(Java)

实现OAuth2的密码所有者资源流(Java),java,playframework,oauth-2.0,authorization,Java,Playframework,Oauth 2.0,Authorization,对于我的学士学位论文,我必须用不同的框架实现不同类型的身份验证和授权。 目前im在OAuth2章节中,必须在Play框架(Java)中实现它。(我已经用Spring Boot实现了它) 在研究如何解决这个问题时,到目前为止,我找不到很多有用的提示 我的一个主要问题是:在客户端使用用户凭据对自己进行身份验证并获得令牌后,如何最好地验证令牌? 基本上:与Spring的“@PreAuthorize”注释相对应的剧本是什么 感谢您提供任何有用网站的提示或链接。所以我想我解决了我的问题。万一有人碰到同样的

对于我的学士学位论文,我必须用不同的框架实现不同类型的身份验证和授权。 目前im在OAuth2章节中,必须在Play框架(Java)中实现它。(我已经用Spring Boot实现了它) 在研究如何解决这个问题时,到目前为止,我找不到很多有用的提示

我的一个主要问题是:在客户端使用用户凭据对自己进行身份验证并获得令牌后,如何最好地验证令牌? 基本上:与Spring的“@PreAuthorize”注释相对应的剧本是什么


感谢您提供任何有用网站的提示或链接。

所以我想我解决了我的问题。万一有人碰到同样的问题,我会在这里发布解决方案:

正如使用OAuth2编写的Play Docs()中所述,尤其是使用密码流,它非常简单

首先,您需要一个授权服务,这里的实现是直接的。只需实施三种方法:

POST/oauth/token,用于传递用户凭据并接收访问和刷新令牌

访问令牌不再有效时的POST/oauth/refresh。这里传递刷新令牌,并返回一个新的acces令牌

POST/oauth/check_令牌以获得授权。在这里,访问令牌被传递,在我的例子中,我返回了角色,用户拥有。另外,在授权服务中执行授权过程也是可能的,而且可能更好。为此,您需要更改“check_token”方法并传递所需的角色

我只是将UUID生成为令牌,并将它们存储在数据库中。我想人们也可以使用jwts,并将所需信息(例如过期日期)放入令牌中

然后我的主要问题是关于注释。我找到了这个 看看它们的实现

您基本上只需要一个类和一个接口:

界面:

@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")
    ));

}
私有wsws客户端;
私有最终字符串url=”http://localhost:9001/oauth/check_token";
@注入
公共授权ServerAuthAction(WSClient ws){
this.ws=ws;
}
私有CompletionStage调用API(字符串访问令牌){
CompletionStage eventualResponse=ws.url(url).setContentType(“application/x-www-form-urlencoded”).setRequestTimeout(持续时间.秒(10))
.addHeader(“授权”,accessToken).post(“无”);
返回eventualResponse.thenApply(WSResponse::asJson);
}
@凌驾
公共CompletionStage调用(Http.Context ctx){
可选accessTokenOptional=ctx.request().header(“授权”);
JsonNode结果=null;
如果(!accessTokenOptional.isPresent()){
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“标头中未找到令牌!”)
));
}
CompletionStage apiResponse=callApi(accessTokenOptional.get());
试一试{
结果=apiResponse.toCompletableFuture().get();
}捕获(中断异常|执行异常e){
e、 printStackTrace();
}
如果(结果==null){
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“发生错误”)
));
}
字符串role=result.get(“role”).asText();
if(configuration.requireAdmin()){
if(角色等于(“管理员”)){
返回委托呼叫(ctx);
}否则{
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“用户无权执行此操作!”)
));
}
}else if(configuration.requireResonnel()){
if(角色相等(“人员”)| |角色相等(“管理”)){
返回委托呼叫(ctx);
}否则{
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“用户无权执行此操作!”)
));
}
}else if(configuration.requireGuest()){
if(role.equals(“来宾”)| | role.equals(“人员”)| | role.equals(“管理员”)){
返回委托呼叫(ctx);
}否则{
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“用户无权执行此操作!”)
));
}
}
返回CompletableFuture.completedFuture(未经授权(Json.newObject())
.put(“消息”,“发生错误”)
));
}
}