Java tutorial
/* * * Springstrap * * @author Jan Philipp Knller <info@pksoftware.de> * * Homepage: http://ui5strap.com/springstrap * * Copyright (c) 2013-2014 Jan Philipp Knller <info@pksoftware.de> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * Released under Apache2 license: http://www.apache.org/licenses/LICENSE-2.0.txt * */ package de.pksoftware.springstrap.basic.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import de.pksoftware.springstrap.core.domain.IAccount; import de.pksoftware.springstrap.core.exception.NoSuchAccountException; import de.pksoftware.springstrap.core.service.IAccountService; @Service public class BasicSecurityService { private static final Logger logger = LoggerFactory.getLogger(BasicSecurityService.class); @Autowired private IAccountService accountService; /** * Returns the current logged in Account. * @return */ public IAccount getCurrentAccount() { IAccount account = getCurrentUserDetails(); //We get the entity again by its ID. This is only executed until the entity is in the JPA cache. //This helps to prevent cache side effects produced by JPA cache. if (null != account) { logger.info("Requesting Account for ID " + account.getId()); try { return accountService.loadAccountById(account.getId()); } catch (NoSuchAccountException e) { return null; } } return null; } /** * Get the UserDetails of the current logged in Account. * @return */ public static IAccount getCurrentUserDetails() { SecurityContext securityContext = SecurityContextHolder.getContext(); Authentication auth = securityContext.getAuthentication(); if (null != auth && !(auth instanceof AnonymousAuthenticationToken)) { return (IAccount) auth.getPrincipal(); } return null; } }