I believe I have basic authentication working but I'm not sure how to protect resources so that they can only be accessed when the user is signed in.
public class SimpleAuthenticator implements Authenticator<BasicCredentials, User> {
UserDAO userDao;
public SimpleAuthenticator(UserDAO userDao) {this.userDao = userDao;}
@Override
public Optional<User> authenticate(BasicCredentials credentials) throws AuthenticationException
{
User user = this.userDao.getUserByName(credentials.getUsername());
if (user!=null &&
user.getName().equalsIgnoreCase(credentials.getUsername()) &&
BCrypt.checkpw(credentials.getPassword(), user.getPwhash())) {
return Optional.of(new User(credentials.getUsername()));
}
return Optional.absent();
}
}
My Signin resource is like this:
@Path("/myapp")
@Produces(MediaType.APPLICATION_JSON)
public class UserResource {
@GET
@Path("/signin")
public User signin(@Auth User user) {
return user;
}
}
And I sign the user with:
~/java/myservice $ curl -u "someuser" http://localhost:8080/myapp/signin
Enter host password for user 'someuser':
{"name":"someuser"}
Question
Let's say the user signs in from a browser or native mobile app front end using the /myapp/signin endpoint. How then can I protect another endpoint, say, /myapp/{username}/getstuff which requires a user to be signedin
@GET
@Path("/myapp/{username}/getstuff")
public Stuff getStuff(@PathParam("username") String username) {
//some logic here
return new Stuff();
}