- Published on
Java Security - Part 11: Java Authentication and Authorization Service (JAAS)
- Authors
- Name
- Gary Huynh
- @huynhthienthach
Alrighty, get ready to hoist the mizzenmast and set sail for the glorious land of JAAS
!
JAAS
stands for Java Authentication and Authorization Service
, part of the Java security API
. It's like the trusty ship's lookout in your Java application
, helping ye validate who's friend and who's foe (authentication
), and deciding who gets to swab the deck and who gets to man the helm (authorization
).
Authentication in JAAS
is a two-step process:
- Who goes there? JAAS collects credentials (like
username
andpassword
) from a user trying to access resources in your application. That's like the first watch in the crow's nest asking for apassword
before letting anyone on board. - Alright, ye seem familiar! JAAS
verifies
the collected credentials against an existing store (like adatabase
). That's akin to the second watch checking if ye be in the ship's logbook.
Authorization
, on the other hand, determines what the authenticated user can do in your application. It's like deciding whether a shipmate can man the cannons or should stick to peeling potatoes.
Here's a basic code snippet that shows how to authenticate a user with JAAS
:
import javax.security.auth.login.LoginContext;
import javax.security.auth.login.LoginException;
public class JaasAuthentication {
public static void main(String[] args) {
// 1. Create a LoginContext.
// (a) Pass it a CallbackHandler.
LoginContext lc;
try {
lc = new LoginContext("Sample", new MyCallbackHandler());
// 2. Attempt authentication
lc.login();
} catch (LoginException le) {
System.err.println("Authentication failed:");
System.err.println(" " + le.getMessage());
System.exit(-1);
}
System.out.println("Authentication succeeded!");
}
}
And there ye have it! With JAAS
, you've got yourself a robust system for managing users and their access to resources. Next up on our voyage is Role-Based Access Control
, where we decide whether ye be a lowly deckhand or the Captain himself! Yarrr!