How to sign JWT from a JWKSet file? - jwt

I want to sign JWT token from a local jwk file containing keys in JWKSet. I'm trying to achieve this by loading json file in JWTSet object and then sign the token with it but it through an exception that signer need to have private key. Is there a way to sign jwt from JWKSet? Here is the code snippet:
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.JWSSigner;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import com.nimbusds.jose.crypto.RSASSASigner;
public class testJWK {
public static void main(String[] args) throws IOException, ParseException {
JWKSet jwks = JWKSet.load(new File("./jwkset.json"));
JWSSigner signer = new RSASSASigner(jwks);
}
}

Related

Will Spring Mail module be alternate to javax.mail

I have a Spring boot application where I need to send an alert mail to both a gmail account and a Zoho account. I try to use Javax.mail, where I set the properties of a both Gmail and a Zoho account using Java class and use it. Will Spring mail be a best replacement for Javax.mail. I have a doubt if Spring mail module can be used because we set the SMTP server properties in application.yml
The first thing to do is to import the dependency from Maven Central Repository.
<dependency>
<groupId>it.ozimov</groupId>
<artifactId>spring-boot-email-core</artifactId>
<version>0.5.0</version>
</dependency>
Then, you populate the application.yml with the following entries
spring.mail.host: smtp.gmail.com
spring.mail.port: 587
spring.mail.username: hari.seldon#gmail.com
spring.mail.password: Th3MuleWh0
spring.mail.properties.mail.smtp.auth: true
spring.mail.properties.mail.smtp.starttls.enable: true
spring.mail.properties.mail.smtp.starttls.required: true
Now, for the sake of the example, assume that you have a service that sends a very simple plain text email. It will be something like:
package com.test;
import com.google.common.collect.Lists;
import it.ozimov.springboot.mail.model.Email;
import it.ozimov.springboot.mail.model.defaultimpl.DefaultEmail;
import it.ozimov.springboot.mail.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.mail.internet.InternetAddress;
import java.io.UnsupportedEncodingException;
import static com.google.common.collect.Lists.newArrayList;
#Service
public class TestService {
#Autowired
private EmailService emailService;
public void sendEmail() throws UnsupportedEncodingException {
final Email email = DefaultEmail.builder()
.from(new InternetAddress("hari.seldon#the-foundation.gal",
"Hari Seldon"))
.to(newArrayList(
new InternetAddress("the-real-cleon#trantor.gov",
"Cleon I")))
.subject("You shall die! It's not me, it's Psychohistory")
.body("Hello Planet!")
.encoding("UTF-8").build();
emailService.send(email);
}
}
Let's do it in the main application, where we'll send the email just after starting and initialising the Spring context.
package com.test;
import it.ozimov.springboot.mail.configuration.EnableEmailTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.batch.JobExecutionExitCodeGenerator;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
#SpringBootApplication
#EnableEmailTools
public class PlainTextApplication {
#Autowired
private TestService testService;
public static void main(String[] args) {
SpringApplication.run(PlainTextApplication.class, args);
}
#PostConstruct
public void sendEmail() throws UnsupportedEncodingException, InterruptedException {
testService.sendEmail();
}
}
Observe that to enable the Email Tools you need to annotate the main app with the annotation
#EnableEmailTools
that will trigger the configuration class for the extension.

swagger documentation for hybris

I need to generate rest api documentation using swagger for hybris.
I got Kongchan's sample pom.xml, but I couldn't really modify to match with hybris code. Can anyone pls provide me sample pom.xml for hybris or any links or documents.
Find the Wiki for generating Hybris API Documentation with Swagger
Edit:
You can follow spring-xml-swagger example to integrate it with Hybris using XML configuration. Also, this and this posts will help you.
Here is the class I use for OCC (tested on hybris 6.6)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* #author ajaninmanificat Spring configuration for swagger. Only available if spring profile "swagger" is enabled.
*
*/
#Configuration
#EnableSwagger2
#Profile("swagger")
public class SwaggerConfig extends WebMvcConfigurationSupport
{
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("**/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
#Bean
public Docket api()
{
final ApiInfo apiInfo = new ApiInfoBuilder().title("OCC API documentation")
.description("This document contains the generated API documentation for Omni Commerce Connect v2.")
.version("Version v2").build();
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any())
.build().apiInfo(apiInfo).useDefaultResponseMessages(false).enableUrlTemplating(true);
}
}
To enable Swagger you have to set this property : spring.profiles.active=swagger. The idea is to prevent Swagger from being loaded in production.
To avoid any troubles with BaseSiteMatchingFilter I suggest to create a subclass IgnorableBaseSiteMatchingFilter
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IgnorableBaseSiteMatchingFilter extends BaseSiteMatchingFilter
{
private String regexpIgnore;
#Override
protected void doFilterInternal(final HttpServletRequest request, final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException
{
final boolean shouldIgnore = (regexpIgnore != null) && matchesUrl(request, regexpIgnore);
if (shouldIgnore)
{
filterChain.doFilter(request, response);
}
else
{
// Is not ignored, call the real stuff
super.doFilterInternal(request, response, filterChain);
}
}
public void setRegexpIgnore(final String regexpIgnore)
{
this.regexpIgnore = regexpIgnore;
}
}
And the bean declaration looks like this :
<alias alias="baseSiteMatchingFilter" name="myBaseSiteMatchingFilter" />
<bean id="myBaseSiteMatchingFilter" class="mypackage.IgnorableBaseSiteMatchingFilter" parent="defaultBaseSiteMatchingFilter">
<property name="regexpIgnore" value="(swagger|api-docs|info|login|logout|/health/|/css/|/img/|/js/|/font-awesome/|/bootstrap/|/assets/|/node_modules/)" />
</bean>

HttpServletRequest.getRemoteAddr() is null in rest resource

I have a backend REST application running in glassfish 4.1.
In this simple test resource I want to log the remote address:
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriInfo;
#Path("test")
#RequestScoped
public class TestResource {
private static final Logger LOG = Logger.getLogger(TestResource.class.getName());
#Context
private UriInfo context;
public TestResource() {
}
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getText(#Context HttpServletRequest req) {
LOG.info("TEST - REMOTE ADDRESS: " + req.getRemoteAddr());
throw new UnsupportedOperationException();
}
}
I have nothing "strange" and no proxy (so no "x-forwarded-for" and so on), but when I access the resource I always get null as remote address.
I have googled a lot and tried different solutions with no luck (ie: implementing a filter doesn't work: inside the filter request.getRemoteAddr() is always null).

HTTP Basic Authentication in Restlet with a JAXRS Application?

I'm trying to authenticate access to all resources on my server via HTTP Basic authentication. Currently, my setup looks like this when starting the server:
this.component = new Component();
this.server = this.component.getServers().add(Protocol.HTTP, 8118);
JaxRsApplication application = new JaxRsApplication(component.getContext()
.createChildContext());
application.add(new RestletApplication());
ChallengeAuthenticator authenticator = new ChallengeAuthenticator(
this.component.getContext(),
ChallengeScheme.HTTP_BASIC, "test");
authenticator.setVerifier(new ApplicationVerifier());
this.component.getDefaultHost().attachDefault(authenticator);
this.component.getDefaultHost().attach(application);
this.component.start();
Here's my RestletApplication:
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
public class RestletApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<Class<?>>();
classes.add(TestResource.class);
return classes;
}
}
Here's my ApplicationVerifier:
import java.util.HashMap;
import java.util.Map;
import org.restlet.security.LocalVerifier;
public class ApplicationVerifier extends LocalVerifier {
private Map<String, char[]> localSecrets = new HashMap<String, char[]>();
public ApplicationVerifier() {
this.localSecrets.put("username", "password".toCharArray());
}
#Override
public char[] getLocalSecret(String key) {
if (this.localSecrets.containsKey(key))
return this.localSecrets.get(key);
return null;
}
}
Finally, here's my TestResource:
import java.util.*;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
#Path("test")
public class TestResource {
#GET
#Path("list")
public TestList getTestList() {
return makeTestList();
}
}
However, I'm not seeing any prompt or requirement for authentication when I try to access the resource. What am I doing wrong? I'm not having any issues with marshalling and unmarshalling items and I'm sure that my resource is getting hit with requests. What am I not doing right?
According to the JavaDocs for JaxRsApplication, an authenticator can be set using the following code before starting things up:
((JaxRsApplication)application).setGuard((Authenticator)authenticator);
Do that, and all requests will fly through your authenticator :)

How can I redirect to another page in Servlet using response.sendRedirect() method?

**loginServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String uid=request.getParameter("userid");
String password=request.getParameter("pwd");
if(uid.equals("Anil")&&password.equals("missinlx")){
//out.println("welcome "+uid);
response.sendRedirect("welcomeUser?userid="+uid);
}
else{
out.println("invalid username or password");
}
}
}
**WelcomeUserServlet.java**
package com.anil.apps;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
what is wrong with my code?? I want to redirect the page to welcomeUser.java page using response.sendRedirect() method.
As I am new to servlet please help me out of it. please tell me the whole format for the page redirection in Servlets.
GET parameters are not turned in to variables automatically. You need to add this to the top of your doGet method in the WelcomeUserServlet:
String uid = request.getParameter("userId");
Making that class look like this:
public class WelcomeUserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uid = request.getParameter("userId");
PrintWriter out=response.getWriter();
out.println("<html><body><h1>Welcome " +uid+ "</h1></body></html>");
}
}
You are using the wrong argument for the sendRedirect method
You should use a complete path like
response.sendRedirect("some/path/here/to/"+welcomeUser?userid="+uid)
Or better
response.sendRedirect(response.encodeURL(response.getContextPath()+"welcomeUser?userid="+uid))
Or use a request dispatcher which knows the structure of your project and does not need a full path
request.getRequestDispatcher("welcomeUser?userid="+uid).forward(request,response)