I have a problem getting my JWT Token verified, despite it giving me the correct payload.
Excuse me if I'm a little insecure in this part of the code, since this was handed out by our teacher via a template, but we are unable to reach him.
We had to make some changes to the code itself, since it had the username put into the token and we want the email put in.
We are using something called UserPrincipal, what I can understand, its used to determine access rights to a file or object and originally we used roles to determine what users had access to which endpoints. This is not the case in this project, since its a short demo based on other features.
How does our user principal class look like?
package rest;
import entity.User;
import java.security.Principal;
public class UserPrincipal implements Principal {
private String name;
private String email;
public UserPrincipal(User user) {
this.email = user.getEmail();
}
public UserPrincipal(String email) {
super();
this.email = email;
}
#Override
public String getName() {
return email;
}
}
See, here the user principal used to also get a list of roles and instead of a email, it got a username.
Where do we use this user principal? Well, we use it when we generate our token. This is also here we have our endpoint, yes it should be moved to our interface class.
package rest;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import entity.User;
import facade.UserFacade;
import exceptions.AuthenticationException;
import exceptions.GenericExceptionMapper;
import utils.PuSelector;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
#Path("login")
public class LoginEndpoint {
private static final int TOKEN_EXPIRE_TIME = 1000 * 60 * 30; // ms * sec * min = 30 min
private static final UserFacade USER_FACADE = UserFacade.getInstance(PuSelector.getEntityManagerFactory("pu"));
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response login(String jsonString) throws AuthenticationException {
JsonObject json = new JsonParser().parse(jsonString).getAsJsonObject();
String email = json.get("email").getAsString();
String password = json.get("password").getAsString();
String ip = json.get("ip").getAsString();
try {
User user = USER_FACADE.getVeryfiedUser(email, password, ip);
String code = USER_FACADE.sendCode(email);
String token = createToken(email);
JsonObject responseJson = new JsonObject();
responseJson.addProperty("code", code);
responseJson.addProperty("email", email);
responseJson.addProperty("token", token);
return Response.ok(new Gson().toJson(responseJson)).build();
} catch (JOSEException | AuthenticationException ex) {
if (ex instanceof AuthenticationException) {
throw (AuthenticationException) ex;
}
Logger.getLogger(GenericExceptionMapper.class.getName()).log(Level.SEVERE, null, ex);
}
throw new AuthenticationException("Somthing went wrong! Please try again");
}
private String createToken(String email) throws JOSEException {
//String firstNameLetter = user.getFirstName().substring(0, 1);
//String lastNameLetter = user.getLastName().substring(0, 1);
//int ageTimesID = user.getAge() * user.getId();
//String name = firstNameLetter + lastNameLetter + ageTimesID;
String issuer = "the_turtle_troopers";
JWSSigner signer = new MACSigner(SharedSecret.getSharedKey());
Date date = new Date();
JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
.subject(email)
.claim("email", email)
.claim("allowed", true)
.claim("issuer", issuer)
.issueTime(date)
.expirationTime(new Date(date.getTime() + TOKEN_EXPIRE_TIME))
.build();
SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet);
signedJWT.sign(signer);
return signedJWT.serialize();
}
}
We have a security context class.. Not quite sure if this has any impact on my problem, but regardless:
package rest;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.SecurityContext;
import java.security.Principal;
public class JWTSecurityContext implements SecurityContext {
UserPrincipal user;
ContainerRequestContext request;
public JWTSecurityContext(UserPrincipal user, ContainerRequestContext request) {
this.user = user;
this.request = request;
}
#Override
public boolean isUserInRole(String role) {
return true;
}
#Override
public boolean isSecure() {
return request.getUriInfo().getBaseUri().getScheme().equals("https");
}
#Override
public Principal getUserPrincipal() {
return user;
}
#Override
public String getAuthenticationScheme() {
return "JWT"; //Only for INFO
}
}
And finally we have our JWTAuthenticationFilter:
package rest;
import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSVerifier;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.SignedJWT;
import exceptions.AuthenticationException;
import javax.annotation.Priority;
import javax.annotation.security.DenyAll;
import javax.annotation.security.PermitAll;
import javax.annotation.security.RolesAllowed;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
#Provider
#Priority(Priorities.AUTHENTICATION)
public class JWTAuthenticationFilter implements ContainerRequestFilter {
private static final List<Class<? extends Annotation>> securityAnnotations
= Arrays.asList(DenyAll.class, PermitAll.class, RolesAllowed.class);
#Context
private ResourceInfo resourceInfo;
#Override
public void filter(ContainerRequestContext request) throws IOException {
if (isSecuredResource()) {
String token = request.getHeaderString("x-access-token");//
if (token == null) {
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes(token, 403));
return;
}
try {
UserPrincipal user = getUserPrincipalFromTokenIfValid(token);
//What if the client had logged out????
request.setSecurityContext(new JWTSecurityContext(user, request));
} catch (AuthenticationException | ParseException | JOSEException ex) {
Logger.getLogger(JWTAuthenticationFilter.class.getName()).log(Level.SEVERE, null, ex);
request.abortWith(exceptions.GenericExceptionMapper.makeErrRes("Token not valid (timed out?)", 403));
}
}
}
private boolean isSecuredResource() {
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceMethod().isAnnotationPresent(securityClass)) {
return true;
}
}
for (Class<? extends Annotation> securityClass : securityAnnotations) {
if (resourceInfo.getResourceClass().isAnnotationPresent(securityClass)) {
return true;
}
}
return false;
}
private UserPrincipal getUserPrincipalFromTokenIfValid(String token) throws ParseException, JOSEException, AuthenticationException {
SignedJWT signedJWT = SignedJWT.parse(token);
//Is it a valid token (generated with our shared key)
JWSVerifier verifier = new MACVerifier(SharedSecret.getSharedKey());
if (signedJWT.verify(verifier)) {
if (new Date().getTime() > signedJWT.getJWTClaimsSet().getExpirationTime().getTime()) {
throw new AuthenticationException("Your Token is no longer valid");
}
String email = signedJWT.getJWTClaimsSet().getClaim("email").toString();
return new UserPrincipal(email);
} else {
throw new JOSEException("User could not be extracted from token");
}
}
}
Hope someone will be able to tell me why it is my token isn't getting validated on jwt.io
Related
I'm using msl4j to interact with microsoft products, e.g. emails, calendars. When I call the user informations (without parameters) this will works fine. But, when I try to read messages from the inbox, the call ended with error 404 ("code":"ResourceNotFound","message":"Resource could not be discovered."). I don't know why. The API Permissions seems correct.
import java.io.IOException;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.DeviceCode;
import com.microsoft.aad.msal4j.DeviceCodeFlowParameters;
import com.microsoft.aad.msal4j.IAccount;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.aad.msal4j.IClientCredential;
import com.microsoft.aad.msal4j.MsalException;
import com.microsoft.aad.msal4j.OnBehalfOfParameters;
import com.microsoft.aad.msal4j.PublicClientApplication;
import com.microsoft.aad.msal4j.SilentParameters;
import com.microsoft.aad.msal4j.UserAssertion;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class AppMSAL4J {
private static String userId;
private static String authority;
private static String clientId;
private static String clientSecret;
private static String tenantId;
private static Set<String> scopes;
public static void main(String args[]) throws Exception {
setUpSampleData();
try {
IAuthenticationResult result = acquireToken();
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
String bodyString = "";
RequestBody body = RequestBody.create(bodyString, mediaType);
String baseUrl = "https://graph.microsoft.com/v1.0/users/" + userId;
String parameters = "";
// parameters = "/mailfolders('Inbox')/messages";
// parameters = "/messages";
Request request = new Request.Builder()
.url(baseUrl + parameters)
.method("GET", null)
.addHeader("Accept", "application/json")
.addHeader("Authorization", "Bearer " + result.accessToken())
.build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static IAuthenticationResult acquireToken() throws Exception {
IClientCredential credential = ClientCredentialFactory.createFromSecret(clientSecret);
ConfidentialClientApplication cca = ConfidentialClientApplication
.builder(clientId, credential)
.authority(authority)
.build();
ClientCredentialParameters parameters = ClientCredentialParameters
.builder(scopes)
.build();
return cca.acquireToken(parameters).join();
}
private static void setUpSampleData() {
userId = "b0f***";
tenantId = "fc2***";
authority = "https://login.microsoftonline.com/" + tenantId;
clientId = "b1a***";
clientSecret = "KJ***";
scopes = Collections.singleton("https://graph.microsoft.com/.default");
}
}
Below is my code
package com.jockeyclub.races.validation;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.springframework.beans.BeanWrapperImpl;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.io.IOException;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class RaceReqConstraintValidator implements ConstraintValidator<RaceReq, Object> {
private String raceNum;
private String raceDate;
private String message;
#Override
public void initialize(RaceReq constraintAnnotation) {
ConstraintValidator.super.initialize(constraintAnnotation);
raceDate = constraintAnnotation.raceDate();
raceNum = constraintAnnotation.raceNum();
}
#Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
String rn = (String) new BeanWrapperImpl(value).getPropertyValue(raceNum);
String rd = (String) new BeanWrapperImpl(value).getPropertyValue(raceDate);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String d = formatter.format(LocalDate.parse(new String((String) rd), DateTimeFormatter.ofPattern("yyyy-MM-dd")));
String u = String.format("https://racing.hkjc.com/racing/information/English/Racing/LocalResults.aspx?RaceDate=%s", d);
try {
URL url = new URL(u);
WebRequest request = new WebRequest(url, HttpMethod.POST);
WebClient webClient = new WebClient();
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.getCookieManager().setCookiesEnabled(true);
HtmlPage page = webClient.getPage(request);
if (page.getElementById("errorContainer") != null) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceDate).addConstraintViolation(); //message: "No race on this date"
return false;
}
if (!raceNum.equals("1") && page.getByXPath(String.format("/html/body/div/div[2]/table/tbody/tr/td[%s]/a", raceNum)).isEmpty()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addPropertyNode(raceNum).addConstraintViolation(); //message: "Invalid race number"
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
this is my validator class wherein I return false under 2 conditions. First if condition will return false if there is no race on that date. Second, if condition will return false if the race number is invalid
Here I want to send different messages if my first if condition returns false and if my second if condition returns false. Is there any way to do this? I have mentioned the messages as comments
I use Java mail APIs from a spring web application to send a weekly email to an outlook mail.
The feature was behaving normally for the first couple of weeks, then without any changes outlook received two emails, the next week three emails were received, then four, then five emails.
The logs set in the Java code indicates that only one email is being sent from the application.
I can't replicate the issue by changing the schedule to send each 15 minutes, or hour, or any shorter interval.
Email controller class
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
#Component
public class WeeklyReportScheduler {
#Autowired
private WeeklyReportService weeklyReportService;
#Scheduled(cron = "${cron.expression}")
public void sendWeeklyReport(){
weeklyReportService.sendWeeklyReport();
}
}
Email service class:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.stereotype.Service;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
#Service
public class WeeklyReportService {
#Value("${weekly.report.mail.subject}")
private String subject;
#Value("${weekly.report.mail.body}")
private String mailBody;
#Value("${mail.body.empty.report}")
private String emptyReportMailBody;
#Value("${receiver}")
private String receiver;
#Autowired
private MailService mailService;
#Autowired
private WeeklyReportLogDao weeklyReportLogDao;
#Autowired
private ProjectService projectService;
#Value("${export.path}")
private String exportDir;
protected final Log logger = LogFactory.getLog(getClass());
public void sendWeeklyReport(){
boolean emptyReport = true;
//retrieving attachment data 'projects'
if(projects.size() != 0){
emptyReport = false;
}
String body = "";
if(emptyReport){
body = emptyReportMailBody;
} else {
body = mailBody;
}
SimpleDateFormat format = new SimpleDateFormat("MM/dd/YYYY");
String dateString = format.format(new Date());
String mailSubject = subject + " " + dateString;
List recipients = new ArrayList<String>();
recipients.add(receiver);
String fileName = mailSubject.replace(" ", "_").replace("/", "_");
WeeklyReportExcelExport excelExport = new WeeklyReportExcelExport(exportDir, fileName);
excelExport.createReport(projects);
File excelFile = excelExport.saveToFile();
File[] attachments = new File[1];
attachments[0] = excelFile;
boolean sent = false;
String exceptionMessage = "";
for(int i=0; i<3; i++){
try {
logger.info("Sending Attempt: " + i+1);
Thread.sleep(10000);
mailService.mail(recipients, mailSubject, body, attachments);
sent = true;
break;
} catch (Exception ex) {
logger.info("sending failed because: " + ex.getMessage() + " \nRe-attempting in 10 seconds");
exceptionMessage = ex.getMessage();
sent = false;
}
}
if(!sent){
weeklyReportLogDao.logFailedReporting(dateString, exceptionMessage);
}
//re-try 3 times in case of mail sending failure
}
MailService class:
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
public class MailServiceImpl implements MailService {
/** The From address for the e-mail. read from ant build properties file */
private String fromAddress;
/** The mail sender. */
private JavaMailSender mailSender;
/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass());
public void mail(List<String> emailAddresses, String subject, String text, File[] attachments) throws MailException {
//System.out.println("mail: "+subject);
MimeMessage message = null;
// Fill in the From, To, and Subject fields.
try {
message = mailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(message, true);
messageHelper.setFrom(fromAddress);
for (String emailAddress : emailAddresses) {
messageHelper.addTo(emailAddress);
}
messageHelper.setSubject(subject);
// Fill in the body with the message text, sending it in HTML format.
messageHelper.setText(text, true);
// Add any attachments to the message.
if ((attachments != null) && (attachments.length != 0)) {
for (File attachment : attachments) {
messageHelper.addAttachment(attachment.getName(), attachment);
}
}
}
catch(MessagingException mse) {
String warnMessage = "Error creating message.";
logger.warn(warnMessage);
throw (new RuntimeException(warnMessage, mse));
}
try {
mailSender.send(message);
} catch (Exception ex){
logger.info("Exception sending message: " + ex.getMessage());
}
}
}
you might have duplicate entries on your argument emailAddresses, try moving it to treeset if you cant ensure duplicate entries from the repository layer
I'm trying to migrate from Spring XML based configuration to Pure Java Configuration, I have configured all the configuration files, but when I try to enter the username and password in login page, it redirects me back to the login page again. I believe the userServiceImpl method is not being invoked because the control is not going there.
Here, I have autowired userServiceImpl method which is implementing UserDetailsService of spring security core credentials.
package com.lw.sms.config;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.lw.sms.CustomAuthenticationSuccessHandler;
import com.lw.sms.UserServiceImpl;
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
#EnableTransactionManagement
#Order(1000)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
#Value("${jdbc.dialect}")
String jdbcDialect;
#Value("${jdbc.driverClassName}")
String jdbcDriverClassName;
#Value("${jdbc.databaseurl}")
String jdbcDatabaseurl;
#Value("${jdbc.username}")
String jdbcusername;
#Value("${jdbc.password}")
String jdbcPassword;
#Autowired
private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
#Autowired
private UserServiceImpl userServiceImpl;
#Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
logger.info("configure auth");
auth.userDetailsService(userServiceImpl);
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Override
public void configure(HttpSecurity http) throws Exception {
logger.info("configure http");
http.httpBasic().disable();
http.authorizeRequests().and().formLogin().loginPage("/login").usernameParameter("employeeId")
.passwordParameter("password").successHandler(customAuthenticationSuccessHandler)
.failureUrl("/login?error").defaultSuccessUrl("/dashboard", true)
.loginProcessingUrl("j_spring_security_check")
.and().logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/logout")
.invalidateHttpSession(true).deleteCookies("JSESSIONID")
.and().sessionManagement().invalidSessionUrl("/logout").maximumSessions(1)
.maxSessionsPreventsLogin(true).expiredUrl("/logout");
http.csrf().disable();
http.authorizeRequests().anyRequest().authenticated();
}
#Bean
public SessionRegistry sessionRegistry() {
logger.info("sessionRegistry");
return new SessionRegistryImpl();
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.lw.sms").addProperties(hibernateProperties());
return builder.buildSessionFactory();
}
#Bean
public LocalSessionFactoryBean hibernateSessionFactory() {
logger.info("sessionFactory");
org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration();
configuration.configure("hibernate.cfg.xml");
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.lw.sms");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
#Bean
public DataSource dataSource() {
logger.info("dataSource");
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(jdbcDriverClassName);
dataSource.setUrl(jdbcDatabaseurl);
dataSource.setUsername(jdbcusername);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
logger.info("transactionManager");
HibernateTransactionManager htm = new HibernateTransactionManager();
htm.setSessionFactory(sessionFactory);
return htm;
}
#Bean
public Properties hibernateProperties() {
logger.info("hibernateProperties");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.dialect", jdbcDialect);
hibernateProperties.setProperty("hibernate.default_schema", "sms");
return hibernateProperties;
}
}
CustomAuthenticationSuccessHandler Code is attached below
package com.lw.sms;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Component;
import com.lw.sms.constants.Constants;
import com.lw.sms.user.entities.EmployeeEntity;
import com.lw.sms.user.entities.EmployeePermissionsEntity;
import com.lw.sms.user.service.UserManagementService;
import com.lw.sms.util.QueryBuilder;
#Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationSuccessHandler.class);
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
#Autowired
#Qualifier("sessionInfo")
private SessionInfo sessionInfo;
#Autowired
#Qualifier("userManagementServiceImpl")
private UserManagementService userManagementService;
#Autowired
private HttpServletRequest httpServletRequest;
#Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
clearAuthenticationAttributes(request);
handle(request, response);
}
protected void handle(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
EmployeeEntity employeeEntity = (EmployeeEntity) principal;
setSessionInformationForEmployee(employeeEntity);
}
if (response.isCommitted()) {
return;
}
startServices();
redirectStrategy.sendRedirect(request, response, "/dashboard");
}
/**
* #param employeeEntity
*
*/
private void setSessionInformationForEmployee(EmployeeEntity employeeEntity) {
try {
WebAuthenticationDetails details = (WebAuthenticationDetails) SecurityContextHolder.getContext()
.getAuthentication().getDetails();
userManagementService.updateLoginInfo(employeeEntity.getUsername(), details.getRemoteAddress());
// setting session information
} catch (Exception e) {
logger.info("Exception while set Session Information For Employee :" + ExceptionUtils.getFullStackTrace(e));
}
}
private void startServices() {
logger.info("Starting Services..");
try {
String domainName = httpServletRequest.getScheme() + "://" + httpServletRequest.getServerName();
if (httpServletRequest.getServerPort() != 0) {
domainName += ":" + httpServletRequest.getServerPort();
}
domainName += httpServletRequest.getContextPath();
Constants.domainName = domainName + "/resources";
} catch (Exception e) {
logger.error("Error in start services :"+ ExceptionUtils.getFullStackTrace(e));
}
}
protected void clearAuthenticationAttributes(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
}
public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
this.redirectStrategy = redirectStrategy;
}
protected RedirectStrategy getRedirectStrategy() {
return redirectStrategy;
}
}
UserServiceImpl Code is attached below
package com.lw.sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lw.sms.user.dao.UserManagementDAO;
import com.lw.sms.user.entities.EmployeeEntity;
#Service("userServiceImpl")
public class UserServiceImpl implements UserDetailsService {
#Autowired
#Qualifier("userManagementDAOImpl")
private UserManagementDAO userManagementDAO;
#Override
#Transactional
public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
EmployeeEntity employeeEntity = userManagementDAO.loadUserByUsername(username);
if (employeeEntity == null) {
ContractorEntity contractorEntity = userManagementDAO.loadUserByUsernameContractor(username);
if(contractorEntity == null)
throw new AuthenticationCredentialsNotFoundException("Invalid Username or Password");
}
if(!employeeEntity.isEnabled())
throw new AuthenticationCredentialsNotFoundException("Employee Disabled");
return employeeEntity;
}
}
Global Exception Handler Code:
package com.lw.sms;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
#SuppressWarnings("deprecation")
#Controller
#ControllerAdvice
public class CustomExceptionHandler extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 3699167829164697594L;
private static final Logger logger = LoggerFactory
.getLogger(CustomExceptionHandler.class);
#ExceptionHandler(AuthenticationCredentialsNotFoundException.class)
#ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView handleLoginExceptions(HttpServletRequest request,
HttpServletResponse response,Exception exception) {
logger.info("Handling exception time error"+ exception.getMessage());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("login");
return modelAndView;
}
#ExceptionHandler(HttpSessionRequiredException.class)
public String handleSessionExpired() {
logger.info("session-expired");
return "logout";
}
#SuppressWarnings("unchecked")
#ExceptionHandler(value = { MissingServletRequestParameterException.class,
ServletRequestBindingException.class, TypeMismatchException.class,
HttpMessageNotReadableException.class,
MethodArgumentNotValidException.class,
MissingServletRequestPartException.class })
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Bad Request")
#ResponseBody
public JSONObject handle400Exception(Exception ex,HttpServletResponse response) {
logger.error("400 Exception" + ex.getMessage());
JSONObject jsonObject=new JSONObject();
jsonObject.put("status", HttpStatus.BAD_REQUEST);
jsonObject.put("success", false);
jsonObject.put("message", ex.getMessage());
try {
response.getOutputStream().write(jsonObject.toString().getBytes(Charset.defaultCharset()));
} catch (IOException e) {
logger.error(ExceptionUtils.getFullStackTrace(e));
}
response.setContentType("application/json; charset=UTF-8");
return jsonObject;
}
#ExceptionHandler(value = { NoSuchRequestHandlingMethodException.class, })
#ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Not Found")
#ResponseBody
public Boolean handle404Exception(Exception ex) {
logger.error("404 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler(value = { HttpRequestMethodNotSupportedException.class,
HttpMediaTypeNotSupportedException.class })
#ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE, reason = "Not Supported")
#ResponseBody
public Boolean handle405Exception(Exception ex) {
logger.error("405 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler(value = { HttpMessageNotWritableException.class,
ConversionNotSupportedException.class })
#ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal Server Error")
#ResponseBody
public Boolean handle500Exception(Exception ex) {
logger.error("500 Exception" + ExceptionUtils.getFullStackTrace(ex));
return false;
}
#ExceptionHandler({ Exception.class })
public ModelAndView handleException(Exception ex, HttpServletRequest request,
HttpServletResponse response) {
logger.info("*****************************************************");
logger.error("Exception: " + ExceptionUtils.getFullStackTrace(ex));
ex.printStackTrace();
logger.info("*****************************************************");
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("logout");
return modelAndView;
}
}
This is my HomeController.
package com.lw.sms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import com.lw.sms.master.service.MasterDataService;
import com.lw.sms.user.entities.EmployeeEntity;
/**
* Handles requests for the application home page.
*/
#Controller("homeController")
public class HomeController {
#Autowired
#Qualifier("masterDataServiceImpl")
private MasterDataService masterDataService;
#Autowired
#Qualifier("sessionInfo")
private SessionInfo sessionInfo;
#GetMapping(value = { "/home", "/", "login" })
public ModelAndView home() {
return new ModelAndView("login");
}
#GetMapping(value = "dashboard")
public ModelAndView dashboard() {
EmployeeEntity user = sessionInfo.getEmployeeEntity();
return new ModelAndView("dashboard", "userDetails", user);
}
// Logout page
#ResponseStatus(code = HttpStatus.UNAUTHORIZED)
#GetMapping(value = "logout")
public String logout() {
return "logout";
}
}
Could you please try adding the successForwardUrl also as below.
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/dashboard").access("IS_AUTHENTICATED_FULLY")
.antMatchers("/j_spring_security_check").access("IS_AUTHENTICATED_ANONYMOUSLY")
.and().formLogin().loginPage("/login").usernameParameter("employeeId").passwordParameter("password")
.successForwardUrl("/dashboard").defaultSuccessUrl("/dashboard", true).failureForwardUrl("/loginfailed")
.loginProcessingUrl("/j_spring_security_check")
.and().logout().logoutSuccessUrl("/logout").invalidateHttpSession(true)
.and().sessionManagement().sessionFixation().none()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
.invalidSessionUrl("/login")
.and().exceptionHandling().accessDeniedPage("/Access_Denied").and().csrf().disable();
I was able to replicate the error.
I had to configure a new bean in SecurityConfig file.
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
#Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setUserDetailsService(userServiceImpl);
authenticationProvider.setPasswordEncoder(passwordEncoder());
return authenticationProvider;
}
I am trying to execute sparql queries from jersey client but the problem that the execution returns 200 status and the result is null.But , when I execute the same query on POSTMAN the status is 200 but the result is not null.
the the code for java client :
package org.jaba.messenger.messenger.client;
import org.apache.commons.codec.EncoderException;
import org.apache.commons.codec.net.URLCodec;
import java.net.URI;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.w3c.dom.Document;
public class restapiClient {
public static void main(String args[])
{
Client client=ClientBuilder.newClient();
//sb simple query
HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("admin", "123123");
client.register(feature);
String query=new String("SELECT * WHERE { ?a ?b ?c }") ;
URLCodec uc = new URLCodec();
String sparqlQueryUri = null;
try
{
sparqlQueryUri=uc.encode(query);
System.out.println("SimpleJerseyClient(): uri = " + sparqlQueryUri);
}catch (EncoderException e)
{
System.err.println(e.toString());
e.printStackTrace();
}
WebTarget target=client.target("http://localhost:8080/qodisco/api/sync-search")
.queryParam("query",sparqlQueryUri);
Invocation.Builder invocationBuilder =target.request();
Response response = invocationBuilder.get();
;
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
}
that is the code of the API that I am connecting to it:
package br.ufrn.dimap.consiste.qodisco.api;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import br.ufrn.dimap.consiste.qodisco.model.entities.Domain;
import br.ufrn.dimap.consiste.qodisco.model.entities.User;
import br.ufrn.dimap.consiste.qodisco.model.enums.TopicType;
import br.ufrn.dimap.consiste.qodisco.services.APIService;
import br.ufrn.dimap.consiste.qodisco.services.FusekiService;
#RestController
#RequestMapping("/api")
public class QoDiscoAPI {
#Autowired
private APIService apiService;
#Autowired
private FusekiService fusekiService;
#RequestMapping(value="/user", method=RequestMethod.POST)
public ResponseEntity<String> addUser(#RequestBody User user){
if(!apiService.addUser(user)){
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
return new ResponseEntity<String>(HttpStatus.CREATED);
}
#RequestMapping(value="/sync-search", method=RequestMethod.GET, produces="text/json")
//#RequestParam("domain") String domain,
public String syncSearch( #RequestParam("query") String query){
return apiService.searchByQuery("Pollution", query);
}
#RequestMapping(value="/async-search", method=RequestMethod.GET, produces="text/json")
public #ResponseBody String asyncSearch(#RequestParam("query") String query, #RequestParam("domain") String domain, #RequestParam("type") int type){
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss.SSS");
Date date = new Date();
String topicName = "qodisco"+auth.getName()+dateFormat.format(date);
TopicType topicType;
switch(type){
case 1:
topicType = TopicType.TIPO1;
break;
case 2:
topicType = TopicType.TIPO2;
break;
case 3:
topicType = TopicType.TIPO3;
break;
default:
topicType = null;
break;
}
if(topicType!=null){
fusekiService.asyncSearch(query, topicName, domain, topicType);
return topicName;
} else{
return null;
}
}
#RequestMapping(value="/resource", method=RequestMethod.POST)
public ResponseEntity<String> addResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.CREATED);
}
#RequestMapping(value="/resource", method=RequestMethod.PUT)
public ResponseEntity<String> updateResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.OK);
}
#RequestMapping(value="/resource", method=RequestMethod.DELETE)
public ResponseEntity<String> removeResource(#RequestParam("domain") String domain,
#RequestParam("data") String data){
apiService.createOrUpdateResource(domain, data);
return new ResponseEntity<String>(HttpStatus.OK);
}
#RequestMapping(value="/repository", method=RequestMethod.POST)
public ResponseEntity<String> addRepository(#RequestParam("domains") List<String> domainNames,
#RequestParam("url") String repositoryUrl, #RequestParam("operations") List<String> operations){
if(apiService.addRepository(domainNames, repositoryUrl, operations)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/repository", method=RequestMethod.DELETE)
public ResponseEntity<String> removeRepository(#RequestParam("url") String url){
if(apiService.removeRepository(url)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.GET, produces="text/json")
public List<Domain> getRdos(HttpServletResponse response){
return apiService.getDomains();
}
#RequestMapping(value="/rdo", method=RequestMethod.POST)
public ResponseEntity<String> addRdo(#RequestBody Domain domain){
System.out.println(domain);
if(apiService.addRdo(domain)){
return new ResponseEntity<String>(HttpStatus.OK);
}else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.DELETE)
public ResponseEntity<String> removeRdo(#RequestParam("name") String name){
if(apiService.removeDomain(name)){
return new ResponseEntity<String>(HttpStatus.OK);
} else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
#RequestMapping(value="/rdo", method=RequestMethod.PUT)
public ResponseEntity<String> updateRdo(#RequestBody Domain domain){
if(apiService.addRdo(domain)){
return new ResponseEntity<String>(HttpStatus.OK);
}else{
return new ResponseEntity<String>(HttpStatus.CONFLICT);
}
}
}
that is the result of running the client :
SimpleJerseyClient(): uri = SELECT+*+WHERE+%7B+%3Fa+%3Fb++%7D
200
org.glassfish.jersey.client.internal.HttpUrlConnector$2#cd3fee8
null
Thanks
This could be caused by a parsing error on the side of the endpoint. I've found that Fuseki (is that your underlying triple store?) requires spaces to be encoded as %20 rather than +. However, I managed to run + encoded queries from the browser just fine. Perhaps replacing + with %20 in the encoded query string will resolve the issue. Otherwise, hope someone finds this useful.
sparqlQueryUri = uc.encode(query).replaceAll("\\+", "%20");