Implementing the /authorize/jwt/token API 

Let's write a skeleton of the controller class:

  1. Create an AuthenticationController class. The @Path annotation is used in the   AuthenticationController class. @Path is from the jersey library, and this annotation maps the URI with /authorize to this class.
  2. Inject CustomAuthMechanism and HttpMessageContext, which will be used with AuthMechanism to authenticate the user's credentials.
  3. Create a function called  issueJwt() with the @Path annotation. This maps the URI with /authorize/jwt/token to the issueJwt() function:
@Path("/authorize")
class AuthenticationController {

@Inject
private lateinit var customAuthMechanism: CustomAuthMechanism

private val httpMessageContextImpl: HttpMessageContextImpl =
HttpMessageContextImpl(CallBackHandlerImpl(), MessageInfoImpl(), Subject())

@POST
@Path("/jwt/token")
@Produces(MediaType.APPLICATION_JSON)
fun issueJwt(@Context httpServletRequest: HttpServletRequest,
@Context httpServletResponse: HttpServletResponse): Response {
}
  1. The issueJwt() function takes httpServletRequest and httpServletResponse as parameters. Let's add code to validate the user's credentials coming in via the request and to create a jwt token. The issueJwt() implementation looks as follows:
fun issueJwt(@Context httpServletRequest: HttpServletRequest,
@Context httpServletResponse: HttpServletResponse): Response {
val isValid = customAuthMechanism.validateRequest(httpServletRequest, httpServletResponse,
httpMessageContextImpl)
if (isValid == AuthenticationStatus.SUCCESS) {
var jwt: String = createJwt("1234", "localhost", "subject", 900000L)
var resBody: JSONObject = JSONObject("{"JWT":$jwt}")
return Response.status(Response.Status.OK).entity(resBody).build()
} else {
return Response.status(Response.Status.UNAUTHORIZED).entity("invalid credentials").build()
}
}

Following a successful authentication, the createJwt() function will be invoked, creating the jwt token. Note that the expiry time is set to 900000L, which is equivalent to 15 minutes. The code for the createJwt() and validateRequest() functions is the same as we discussed in Chapter 9Securing JAVA EE Applications with Kotlin. The jwt token will be wrapped around the JSONObject and a response with status code 200 will be returned. If the passed credentials are invalid, a response with status code 401 will be returned.

Let's verify this behavior with the following curl command:

curl -X POST 
http://localhost:8080/authentication-service/authorize/jwt/token
-H 'Accept: application/json'
-H 'Content-Type: application/json'
-H 'UserId: testUser'
-H 'Password: ************'

This gives the following output:

The /authorize/jwt/token API responds with the JWT token.

Let's invoke the API with invalid credentials. This will give us the 401 status code:

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

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