Reputation: 53
I want to create an anotation that will be called in some controllers for checking authentication.
In older play versions until 2.1, i used this following code for overriding call action of Play :
public class OAuth2Action extends Action<OAuth2> {
// ...
@Override
public Result call(Http.Context context) throws Throwable
{
if (authorization == null )
return unauthorized(ACCESS_TOKEN_NOT_FOUND);
return delegate.call(context);
}
}
It returns Result then it could easily returned unauthorized responses with http status code 401 like in Controller
In play 2.2 call method was changed and must return F.Promise
I wrote this following to make it work :
public class OAuth2Action extends Action<OAuth2> {
// ...
@Override
public F.Promise<SimpleResult> call(Http.Context context) throws Throwable {
if (authorization == null ) {
// return unauthorized(ACCESS_TOKEN_NOT_FOUND); // Now i can't use this
// I can set Header, Content type, cookies, BUT NOT STATUS CODE
context.response().setHeader("Header", "test");
}
return delegate.call(context);
}
}
I wish to return response with Status code 401, could you help me to resolve this issue.
Upvotes: 0
Views: 2175
Reputation: 6164
Try this:
public class OAuth2Action extends Action<OAuth2> {
// ...
@Override
public F.Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
if (authorization == null ) {
return F.Promise.promise(new F.Function0<SimpleResult>() {
@Override
public SimpleResult apply() throws Throwable {
return unauthorized(ACCESS_TOKEN_NOT_FOUND);
}
});
}
return delegate.call(ctx);
}
}
Upvotes: 2