Basic authentication mechanism

Basic authentication mechanisms can be achieved by annotating the resource to secure (that is, a servlet or JAX-RS RESTful web service) with the @BasicAuthenticationMechanismDefinition annotation:

package net.ensode.javaee8book.security.basicauthexample; 
 
import java.io.IOException; 
import javax.annotation.security.DeclareRoles; 
import javax.security.enterprise.authentication.mechanism.http.BasicAuthenticationMechanismDefinition; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.HttpConstraint; 
import javax.servlet.annotation.ServletSecurity; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
 
@BasicAuthenticationMechanismDefinition( 
        realmName = "Book Realm" 
) 
@WebServlet(name = "SecuredServlet", 
urlPatterns = {"/securedServlet"}) @DeclareRoles({"user", "admin"}) @ServletSecurity( @HttpConstraint(rolesAllowed = "admin")) public class SecuredServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException { response.getOutputStream().
print("Congratulations, login successful."); } }

The value of the realmName attribute of the @BasicAuthenticationMechanismDefinition annotation will be sent to the browser in the WWW-Authenticate response header.

Using basic authentication will cause the browser to pop up a window asking for a User Name and a Password:

Once the user enters the correct credentials, then access is granted to the protected resource:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.250.203