跳至主要内容

博文

目前显示的是 2017的博文

Java EE Security API 1.0: SecurityContext

SecurityContext In Java EE 7 or earlier versions, other specfications, such as Servelt, EJB, JAX-RS, JAX-WS, etc. have their own specific APIs to query current security context.
Servlet - HttpServletRequest#getUserPrincipal, HttpServletRequest#isUserInRoleEJB - EJBContext#getCallerPrincipal, EJBContext#isCallerInRoleJAX-WS - WebServiceContext#getUserPrincipal, WebServiceContext#isUserInRoleJAX-RS - SecurityContext#getUserPrincipal, SecurityContext#isUserInRoleJSF - ExternalContext#getUserPrincipal, ExternalContext#isUserInRoleCDI - @Inject PrincipalWebSockets - Session#getUserPrincipal In Java EE 8, you can use the new SecurityContext introduced in Java EE Security 1.0 instead.
A default implementation should be available at runime, you can inject it in CDI beans.
@InjectSecurityContext securityContext; The new SecurityContext provides similiar methods with the one in other specfications.
Principal getCallerPrincipal(); <T extends Principal> Set<T> getPrincipalsByType(Cl…

Java EE Security API 1.0: IdentityStore

There are two built-in IdentityStore implementations provided in Glassfish v5, Database or Ldap.
An example of using built-in @DatabaseIdentityStoreDefinition to setup database based IdentityStore.
@DatabaseIdentityStoreDefinition( dataSourceLookup="${'java:global/MyDS'}", callerQuery="#{'select password from caller where name = ?'}", groupsQuery="select group_name from caller_groups where caller_name = ?", hashAlgorithm=Pbkdf2PasswordHash.class, priorityExpression="#{100}", hashAlgorithmParameters= { "Pbkdf2PasswordHash.Iterations=3072", "${applicationConfig.dyna}" } // just for test / example ) @ApplicationScoped@NamedpublicclassApplicationConfig { publicString[] getDyna() { returnnewString[]{"Pbkdf2PasswordHash.Algorithm=PBKDF2WithHmacSHA512", "Pbkdf2PasswordHash.SaltSizeBytes=64"}; } } Initializes database with the initial u…

Java EE Security API 1.0: HTTP authentication

HTTP authenticationHttpAuthenticationMechanism allow customsize your own HTTP authentication mechanism.
An examples for custom HttpAuthenticationMechanism.
@ApplicationScopedpublicclassTestAuthenticationMechanismimplementsHttpAuthenticationMechanism { @InjectprivateIdentityStoreHandler identityStoreHandler; @OverridepublicAuthenticationStatusvalidateRequest(HttpServletRequestrequest, HttpServletResponseresponse, HttpMessageContexthttpMessageContext) throwsAuthenticationException { finalString name = request.getParameter("name"); finalString pwd = request.getParameter("password"); if (name !=null&& pwd !=null ) { // Get the (caller) name and password from the request// NOTE: This is for the smallest possible example only. In practice// putting the password in a request query parameter is highly// insecurePassword password =newPassword(pwd); // Delegate the {credentials in -> identity data out} …

Servlet 4.0: Http Trailer

Http Trailer Servlet 4.0 added Http Trailer(RFC 7230) supports, which is a specific collection of http headers comes after response body.
It is useful in some case, such as chunked transfer encoding or implements some specific protocols.
The reading side, HttpServletRequest has a method isTrailerFieldsReady() to check if the trailer fields are available, if it returns true, the trailer fields can be read via getTrailerFields() method.The writing side, HttpServletResponse has a method setTrailerFields, which accpets a Supplier as it's parameter. An example of Http Trailer to handle chunked tranfer encoding.
@WebServlet("/test") publicclassTestServletextendsHttpServlet { @OverrideprotectedvoiddoPost(HttpServletRequestreq, HttpServletResponseres) throwsServletException, IOException { res.setContentType("text/plain"); res.addHeader("Transfer-encoding", "chunked"); res.addHeader("TE", "trail…

Servlet 4.0: Runtime Discovery of Servlet Mappings

Runtime Discovery of Servlet Mappings When a servlet is activated, the mapping info can be discoverable at runtime.
Described in the Servlet spcefication.
The method getHttpServletMapping() on HttpServletRequest returns an HttpServletMapping implementation that provides information for the mapping that caused the current Servlet to be invoked. Please see the javadocs for the normative specification. Please see sections Section 9.3.1, “Included Request Parameters” on page 9-101Section 9.4.2, “Forwarded Request Parameters” on page 9-102 and Section 9.7.2, “Dispatched Request Parameters” on page 9-104 for relevant request attributes.
But please notice:
As with the included and forwarded request parameters, the HttpServletMapping is not available for servlets that have been obtained with a call to ServletContext.getNamedDispatcher().
An sample to print the mapping information of a servlet.
@WebServlet(name="MyServlet", urlPatterns= { "/MyServlet"…

Servlet 4.0: HTTP/2 Server PUSH

Server Push One highlight feature of HTTP/2 is Server Push. Servlet 4.0 add PushBuilder to handle push.
An exmaple of enable Servlet Push.
@WebServlet(urlPatterns="") @ServletSecurity(httpMethodConstraints={ @HttpMethodConstraint(value="GET", transportGuarantee=CONFIDENTIAL) }) publicclassPushServletextendsHttpServlet { @OverrideprotectedvoiddoGet(HttpServletRequestreq, HttpServletResponseres) throwsIOException, ServletException { PushBuilder pushBuilder = req.newPushBuilder(). path("main.css"); pushBuilder.push(); res.getWriter().println("<html><head><title>HTTP2 Test</title><link rel=\"stylesheet\" href=\"main.css\"></head><body>Hello Servlet Push!!!</body></html>"); } } Run this application on Glassfish v5 in NetBeans IDE, it will open https://localhost:8181/servlet-push/ in browser instead of http://local…

JAX-RS 2.1: Server Sent Event

Server Sent Event Jersey itself supports SSE for years, now it is standardized as a part of JAXRS 2.1.
A simple SSE example.
@Path("events") @RequestScopedpublicclassSseResource { @GET@Produces(MediaType.SERVER_SENT_EVENTS) publicvoideventStream(@ContextSsesse, @ContextSseEventSinkeventSink) { // Resource method is invoked when a client subscribes to an event stream.// That implies that sending events will most likely happen from different// context - thread / event handler / etc, so common implementation of the// resource method will store the eventSink instance and the application // logic will retrieve it when an event should be emitted to the client.// sending events: eventSink.send(sse.newEvent("event1")); } } Notice, you should declare @Produces value as text/event-stream( via MediaType.SERVER_SENT_EVENTS). SseEventSink should be request aware, Sse is helpful to build event payloads etc.
An example of Sse client.
WebTarget ta…

JAX-RS 2.1: Reactive Client

Reactive Client In JAXRS 2.0, a client to handle async resources looks like.
publicclassAsyncClient { publicfinalstaticvoidmain(String[] args) throwsException { WebTarget target =ClientBuilder.newClient().target("http://localhost:8080/jaxrs-async/rest/ejb"); Future<String> future = target.request() .async() .get(String.class); System.out.println("ejb resource future:"+ future.get()); target.request() .async() .get(AsyncClient.responseInvocationCallback()); } privatestaticInvocationCallback<Response>responseInvocationCallback() { returnnewInvocationCallback<Response>() { @Overridepublicvoidcompleted(Responseres) { System.out.println("Status:"+ res.getStatusInfo()); System.out.println("Entity:"+ res.getEntity()); System.out.println("Request succe…