Java tutorial
/* Copyright 2013 Mael Le Guvel This work is free. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See the COPYING file for more details. */ package fr.mael.microrss.util; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Component; import fr.mael.microrss.domain.User; @Component public class SecurityUtil { @Autowired private Configuration configuration; public String random() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(configuration.getSaltAlgorithm()); // Salt generation 64 bits long byte[] bSalt = new byte[8]; random.nextBytes(bSalt); return Base64.encodeBase64String(bSalt); } public User getCurrentUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); Object principal = auth.getPrincipal(); if (principal == null || !(principal instanceof User)) { throw new AccessDeniedException("User is not logged in"); } User user = (User) principal; //TODO the id is lost when the server is restarted //will it happen in production ? if (user.getId() == null) { throw new AccessDeniedException("User is not logged in"); } return user; } }